Code Monkey home page Code Monkey logo

angular-validator's Introduction

Angular-Validator

Build Status

Angular-Validator is an easy to use, powerful and lightweight AngularJS validation directive.

Demo

Check out the demo!

Features

  • Validate using regex, HTML5, or custom validation functions.
  • Works seamlessly with all native AngularJS validation directives and native HTML5 validation attributes.
  • Supports custom validation message templates and placement using Angular's native ngMessages directive.
  • Choose when to validate elements, on per-element basis. Choose between on form submission, blur or dirty(change).
  • All validation states and validation messages are accessible through $scope.yourFormName.elementName.
  • Prevents submission if the form is invalid
  • Built in reset() form method
  • Supports multi-field dependent validation (one field depends on another such as password matching)
  • Works with Bootstrap out of the box (although Bootstrap is not required)
  • Optionally adds .has-error classes to invalid form and message message elements so you don't have to.
  • Supports form invalid message service where manage invalid messages in one place and save code in HTML

Why?

Despite Angular's awesomeness, validation in Angular is still annoying. Surprisingly there are no seamless, user-friendly, well written Angular validation tools. Unlike other Angular validation tools, Angular-Validator works with out-of-the-box Angular and HTML5 validation, directives and attributes, allowing your forms to work well with the browser and other Javascript code.

Installation

  1. Using bower: bower install tg-angular-validator.
  2. Include angular-validator.min.js.
  3. Add angularValidator as a dependency of your Angular module.

Usage

Basic usage for required fields

<input  type = "text"
        name = "firstName"
        ng-model = "person.firstName"
        required>

Usage with a custom validator function

<input  type = "text"
        name = "firstName"
        ng-model = "person.firstName"
        validator = "myValidationFunction(person.firstName)">

Usage with validation on blur

<input  type = "text"
        name = "firstName"
        ng-model = "person.firstName"
        validate-on="blur"
        validator = "myValidationFunction(person.firstName)">

Usage with validation on dirty

<input  type = "text"
        name = "firstName"
        ng-model = "person.firstName"
        validate-on="dirty"
        validator = "myValidationFunction(person.firstName)">

Usage with custom validator literal

<input  type = "text"
        name = "firstName"
        ng-model = "person.firstName"
        validator = "person.firstname === 'john'">

Usage with REGEX and required

<input  type = "text"
        name = "firstName"
        ng-model = "person.firstName"
        ng-pattern = "/regex/"
        required>

Usage with custom error message text

<input  type = "text"
        name = "firstName"
        ng-model = "person.firstName"
        ng-pattern = "/regex/"
        invalid-message = "'Please enter the word regex'"
        required-message = "'First name is required'"
        required>

Usage with conditional invalid/required message text

<input  type = "text"
        name = "firstName"
        ng-model = "person.firstName"
        validator= "myValidationFunction(person.firstName) === true"
        invalid-message = "myValidationFunction(person.firstName)"
        required-message = "myValidationFunction(person.firstName)"
        required>
  • Note that the validator and the message function do not need to be the same function. If you choose to make them the same function make sure to return true on valid input.

Usage without auto-generated error label

<input  type = "text"
        name = "firstName"
        ng-model = "person.firstName"
        validator= "myValidationFunction(person.firstName) === true"
        required
        angular-validator-quiet>

Use angular-validator-quiet on an element to prevent the auto-generation of new DOM element label after this inputs. You then have complete control over the location and classes used to show the error messages.

Setting up the form

<form novalidate angular-validator angular-validator-submit='myOnSubmitFunction()' name='myFormName'>
    ....
    ....
    <button type='submit'>Submit</button>
</form>

Use angular-validator-submit to specify the function to be called when the form is submitted. Note that the function is not called if the form is invalid.

Use form invalid message service

<form novalidate angular-validator invalid-message='customMessage' angular-validator-submit='submitMyForm()' name='myFormName'>
        <input  type='text'
                name='firstName'
                validate-on='dirty'
                ng-model='firstName'>
</form>

Use invalid-message on form element to provide the name of the service in which invalid messages are managed. You need to provide a message function in your service, which returns the messages you defined. Form invalid message service saves repetitive code in HTML because you do not need to use invalid-message attribute on every field. Please see the demo for examples.

Usage form without auto-generated error label

<form novalidate angular-validator angular-validator-submit="submitMyForm()" name="myFormName" angular-validator-quiet>

Use angular-validator-quiet on form element to prevent the auto-generation of new DOM element label after all of this forms inputs.

Resetting the form

myFormName.reset()

You need to include a name attribute on the form to use this.

Validity API Uses standard Angular $valid and $invalid properties so that it can work with core angular and third party libraries!

formName.$invalid
formName.$valid
elementName.$valid
elementName.$invalid
elementName.$angularValidator

FAQ

It's not working!? Make sure you have assigned a unique name to each form element as well as the form itself. Make sure you have properly followed the installation instructions.

Why pass value to custom validator functions? Passing the value to the custom validator function allows the function to be easier to test.

How do I display success messages/classes? The library does not currently support success classes and messages. Feel free to contribute.

What if I want error messages to display before the user types anything? You are using the wrong library.

What if I want to disable the submit button if the form is invalid? You can add ng-disabled="myForm.$invalid" on the submit button.

CONTRIBUTING

See CONTRIBUTING.md

License

MIT

angular-validator's People

Contributors

andersonrocha avatar codonist avatar czarly avatar dlear avatar floriansimon1 avatar fscv avatar jakobovski avatar jonbern avatar jslain avatar lydongray avatar neilsh avatar qwlong avatar webmato avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular-validator's Issues

How can i reset the validators in the form

First of all thanks for this small, beautiful and very helpful validation library.

and now issue.

I have used dirty validation on my form which works perfectly but i want to have a reset button on the form so that when i click reset it should clear the form data and also the validations.
i.e i want all the red lines of validation disappear when i click on reset

utf-8 encoding in require-message

i set require-message to some Farsi characters and i see this error in my browser when i submit
form :

Error: [$parse:lexerr] Lexer Error: Unexpected next character at columns 0-0 [آ] in expression [آدرس پست الکترونیکی را وارد کنید].

how can resolve this error?

integrating with angular-formly

Hi,

how does it integrate with angular-formly ? the form is generated dynamically using json fields. so just wanted to check if anyone has done any integrated validator with formly ?

thx
sri

focus on first invalid element

Hi,

not sure if its already in place, but just wanted to check if theres a way to focus on the first invalid element on errors ?

thx
sri

Form names with dots aren't supported

Hey all,

Discovered that the dot in my form name was throwing an exception. I tried checking to make sure that dots are allowed in the name attribute (per HTML spec) before I raised an issue over it, and I actually couldn't find a definitive yes or no.

However AngularJS's form directive does support dots in the names.

I have a pull request open with a suggested fix; any thoughts?

I'm noticing now that there might be more places in the code that could suffer from the same bug, but before I go making the pull request a larger diff I figured I'd wait on some feedback.

Thanks.

Validation method with $http call brings angular.$digest loop and throws Exception

I add http call to validation method and get such error.

    at XMLHttpRequest.requestLoaded (angular.js:10469)(anonymous function) @ angular.js:12314$get @ angular.js:9101$get.Scope.$apply @ angular.js:15937done @ angular.js:10356completeRequest @ angular.js:10528requestLoaded @ angular.js:10469
angular.js:68 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.1/$rootScope/infdig?p0=10&p1=%5B%5DREGEX_STRING_REGEXP @ angular.js:68$get.Scope.$digest @ angular.js:15705$get.Scope.$apply @ angular.js:15935done @ angular.js:10356completeRequest @ angular.js:10528requestLoaded @ angular.js:10469
api.ru/api/v1/users/check:1 POST http://api.ru/api/v1/users/check 404 (Not Found)
angular.js:12314 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.1/$rootScope/infdig?p0=10&p1=%5B%5D
    at REGEX_STRING_REGEXP (angular.js:68)
    at Scope.$get.Scope.$digest (angular.js:15705)
    at Scope.$get.Scope.$apply (angular.js:15935)
    at done (angular.js:10356)
    at completeRequest (angular.js:10528)
    at XMLHttpRequest.requestLoaded (angular.js:10469)(anonymous function) @ angular.js:12314$get @ angular.js:9101$get.Scope.$apply @ angular.js:15937done @ angular.js:10356completeRequest @ angular.js:10528requestLoaded @ angular.js:10469
angular.js:68 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.1/$rootScope/infdig?p0=10&p1=%5B%5DREGEX_STRING_REGEXP @ angular.js:68$get.Scope.$digest @ angular.js:15705$get.Scope.$apply @ angular.js:15935done @ angular.js:10356completeRequest @ angular.js:10528requestLoaded @ angular.js:10469
api.ru/api/v1/users/check:1 POST http://api.ru/api/v1/users/check 404 (Not Found)
angular.js:12314 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.1/$rootScope/infdig?p0=10&p1=%5B%5D
    at REGEX_STRING_REGEXP (angular.js:68)
    at Scope.$get.Scope.$digest (angular.js:15705)
    at Scope.$get.Scope.$apply (angular.js:15935)
    at done (angular.js:10356)
    at completeRequest (angular.js:10528)
    at XMLHttpRequest.requestLoaded (angular.js:10469)(anonymous function) @

My input

 <div class="form-group">
                    <input type="text" 
                    ng-model="username"
                    placeholder="Имя пользователя" 
                    name="username"
                    required
                   validator = "validateUsername(username) === true"
                   required-message="'Введите имя пользователя'"
                   invalid-message = "anotherCustomValidator(form.myField)"
                   autofocus="autofocus"
                   class="form-control decorative-input"/>

                </div>

Breaks Bootstrap input add-on layout on error

When Bootstrap add-on is used with input element (div with CSS class "input-group-addon"), it is broken by error label.
input_addon
input_addon_broken

<div class="form-group">
    <label for="myField" class="col-sm-6 control-label">My field</label>
    <div class="input-group col-sm-4">
        <input type="number"
               name="myField"
               class="form-control input-sm"
               id="myField"
               required
               ng-model="myField"
               validate-on="dirty" />
        <div class="input-group-addon">%</div>
    </div>
</div>

Form elements inside ng-if are getting ignored

Hey, I have some inputs that are usually hidden on page load, and then when a value in the model changes, they get shown. One looks like such:

<span class="input-group" ng-if="specs.valueType == 'static'">
                                        <input class="form-control" ng-model="specs.value" 
                                               validation-label="specValueLabel" 
                                               name="specValue" 
                                               required 
                                               />
                                        <label name="specValueLabel"></label>
                                    </span>

From what I can tell, because the watchers get attached on form render, I'm wonder if you know how to account for inputs getting added later on. If I use a ng-show instead, then some inputs that are hidden would get validated when they're not needed within the context of the form.

Here's a plnkr. http://plnkr.co/edit/N3pbGR61LfFfyYnK8rFB?p=preview

If you select the first option 'some', the box shows up and it gets validated on submit, but the message doesn't show if you leave it blank. When you select 'other', the form submits just fine. I need it to show the message on the input if it's visible and invalid.

Thanks

making an element invalid in controller

hi,

is there a way I show the error message by setting $invalid to false on form element in controller function ? pls. let me know if this is something I can achieve.

I have a field which fires a ajax request on update and I want to invalidate/validate the input based on
response.

thx
sri

Doesnt work with ng-repeat. :(

It doesnt work with ng-repeat.
For example I have a part of form like this:

<div ng-repeat="lang in langs">
        <label class="col-md-4 col-xs-12">
            <div class="col-md-12 col-xs-12">
                <input ng-model="objClass.title[lang]" name="title[lang]"
                       required
                       required-message = "'required!'"
                       class="form-control input-sm">
            </div>
        </label>
</div>

Can you help to solve this problem?

Dynamically created fields do not modify the form's $invalid state.

Hi, great plugin.

The issue i am having is that I am not sure how to get angular-validator to $watch fields that have been added with $compile and .append() to the form.

So currently, after an .append(), the wrapping form's validation isn't changed even if the field is invalid.

Any suggestions/ideas would be greatly appreciated.

Thanks.

one controller multi form error TypeError: Cannot read property 'submitted' of undefined

when i use angular-validator in one controller, i receive the error, like this

TypeError: Cannot read property 'submitted' of undefined
    at updateValidationMessage (angular-validator.js:175)
    at Object.fn (angular-validator.js:104)
    at Scope.$get.Scope.$digest (angular.js:14308)
    at Scope.$get.Scope.$apply (angular.js:14571)
    at done (angular.js:9698)
    at completeRequest (angular.js:9888)
    at XMLHttpRequest.requestLoaded (angular.js:9829)

after I debug
I think we should change

line 175

 if (scopeElementModel.$dirty || scope[element.form.name].submitted) {

to

if (scopeElementModel.$dirty || scope[element.form.name] && scope[element.form.name].submitted) {

line 235

if (formField.$dirty || scope[element.form.name].submitted) {

to

if (formField.$dirty || scope[element.form.name] && scope[element.form.name].submitted) {

ng-if causes problem

ng-if on div.form-group causes excluding element from watching.

In your test adding ng-if="true" leads to validation messages are not shown:

<div class="form-group" ng-if="true">
<label class="col-sm-2 control-label">Regex</label>
<div class="col-sm-10">
<input type = "text"
name = "regex"
class = "form-control"
ng-model = "form.regex"
ng-pattern="/regex/"
invalid-message="'You must enter the word regex'"
required-message="'Yo! This field is required..'"
required>
</div>
</div>

ng-show="true" works well.

Styles are not working with Select

It blocks me from submitting, but there are no error messages or styles applied.

      <div class="form-group" >
        <label class="col-md-3 control-label">Task</label>
        <div class="col-md-5">
          <select class="form-control" ng-model="task_type.id" required
                  ng-options="s.value as s.text for s in taskTypeSelect">
            <option style="display:none" value=""></option>
          </select>
        </div>
      </div>

Resetting Form & Removing Error Messages

I have my form elements in a bootstrap modal window. When i press the submit button it triggers validation and showing error messages for required fields. Now i am closing the modal window and i am trying to open that window again with button click still those error messages are displaying. My situation is to remove all the error messages when i am opening the form again which is already submitted. Do you have any method are configuration to reset and remove the error messages from form? Please let me know how to do this.

TypeError: undefined is not a function - $setModelValue("");

I checked out the v1.2.2 tag and I whenever I try to run the I get the following error:

TypeError: undefined is not a function
at FormController.scopeForm.reset (http://localhost/angular-validator/src/angular-validator.js:27:60)
at $parseFunctionCall (http://localhost/angular-validator/bower_components/angular/angular.js:12336:18)
at callback (http://localhost/angular-validator/bower_components/angular/angular.js:21422:17)
at Scope.$eval (http://localhost/angular-validator/bower_components/angular/angular.js:14388:28)
at Scope.$apply (http://localhost/angular-validator/bower_components/angular/angular.js:14487:23)
at HTMLButtonElement.<anonymous> (http://localhost/angular-validator/bower_components/angular/angular.js:21427:23)
at HTMLButtonElement.eventHandler (http://localhost/angular-validator/bower_components/angular/angular.js:3011:21)angular.js:11598 (anonymous function)angular.js:8548 (anonymous function)angular.js:14489 Scope.$applyangular.js:21427 (anonymous function)angular.js:3011 eventHandler

has-error class in select

I'm validating an select input, the invalid message is showing well, but the color of the label and the border of select is not red. This is because the validator is not adding the 'has-error' class to parent div.

Destructors and cleanup

When fields are wrapped in "ng-if", when toggling forms when they are "processing" throws undefined errors on line 142

scopeForm[element.name].$setValidity("angularValidator", isElementValid);

You need to add a destructor.

In the meantime, I fixed this using ng-hide/show. ng-if completely removes an element - this is good when you're dealing with lots of forms since you only want have watchers for what is actually visible.

Bower Bootstrap dependency should be removed

According to the documentation, angular-validator supports Bootstrap but it's not a requirement. At the same time Bootstrap is listed as a dependency in bower.json. This means Bootstrap and its dependencies (jQuery) will be installed when using angular-validator on a project.

I really like angular-validator and I think it's a big step up compared to the basic Angular way of doing validation. But since my project is not using Bootstrap and jQuery, I can't justify the extra space impact of using angular-validator when it adds both Bootstrap and jQuery to my project.

Would it be possible to remove Bootstrap as a dependency in bower.json?

Also, angular-mocks has been listed as a dependency as well. Shouldn't this be listed as a dev-dependency instead?

bower repo is out of date

An issue isn't really the best way of raising this, but anyway...

The bower repository seems out of date for this; there's no support for "validate-on" in there.

why my validator function is called repeatedly (4/6 times) ?

I have added a validator function and I was debugging the function for some reason and noticed that the validator function is called min of four to six times. any reason why is it called repeatedly ?

and also in IE, the function fail to consider the return value from the validator function. it always show invalid message irrespective of true/false return value.

Missing "var" declaration

This is a minor issue, but I think you have a var declaration missing on isDirtyElement:

// Determine if the element in question is to be updated on blur
isDirtyElement = "validate-on" in ...

regex validation not work properly

i create an input element with this regex validation rule by this code :


and this input must accept (09XXXXXXXXXX) witch every X is a digit but this accept nothing

Chosen and Angular-Validator

Hello,
It's not an issue but need some help.
I use chosen.js library to convert my dropdownlists.
Then when I pass a "Select" tag, chosen converts the tag into a couple of html tags and hides the original select.
My problem when using the angular-validator is the "error message" placeholder comes logically after the "hidden" select tag and before the generated chosen tags.
So intead having the error message at the bottom of the "chosen" dropdownlist, it comes on the top.
Is there a way to handle this effect?
Thanks in advance.

.validationMessage labels shouldn't be removed from DOM

Hi! I tried to animate the display of errors (with a slide down animation) but I couldn't do it because the element label.validationMessage it's been removed / added to the DOM when an error takes place. This element should be created once on instantiation and then make of use of ng-hide so animations can be hooked with ng-animate and CSS.

Just a suggestion :).

Thanks for your module.

Provide a way to customize error messages

I'd like to be able to customize the location and template for error messages, or perhaps better, have it look for a specific, already existing element to populate with a message. I'm working on my own solution with a fork of your directive, but maybe you have some better ideas!

multi field dependent validation

Hi,

I have a scenario where I want to check for required field validation only if a particular checkbox is selected. what do I need to achieve this particular validation ?

is ng-required="checboxValue" is honoured in the input fields with angular-validator ? looks like its not having any impact on the way validations are fired.

thx
sri

ng-pattern error message

Hi, is it possible to distinguish between reg-ex error message and invalid error message ? right now, the reg-ex error is invalid error message. but I want to differentiate between both the error messages, may be introducing one more error-message attribute ?

When closing a modal which contains the form, it attempts to submit?

I'm trying to close/hide a modal when a user clicks 'Cancel' instead of choosing to submit the form. When I hide the modal it automatically submits the form. Is there a proper function to call to cancel submission and prevent calling the function tied to angular-validator-submit?

`validate-on` property

I cannot find any documentation describing what we can do with validate-on. The demo you provide only uses dirty.

Can this be used to trigger validation on a form when other model's value changes?

I need to trigger validation on a field when another (arbitrary) model's value changes.

Changes in ng-required do not update the messages

When I have an element that has ng-required that changes from false to true AFTER the form validation, the message on this element is not shown when the ng-required is changed.

Solution: add 'element.required' to the $watch function, ie:

return elementToWatch.required + elementToWatch.value + scopeForm.submitted + checkElementValididty(elementToWatch) + getDirtyValue(scopeForm[elementToWatch.name]);

Nested Forms

I try to use the library to validate fields in a nested form, which i created with ng-form="innerForm", but the library throws this exception, maybe because it can find the element name in the main form:

TypeError: Cannot read property '$setValidity' of undefined at checkElementValidity (angular-validator.min.js:151)

it doesn´t work with ui-select

Hello, sorry for my English, please help me, i need to use this project with select control, i´m using ui-select project and i need to validate if the user has choosen one option, if not, i need to show a required message. So, am I doing something wrong? or this project doesn´t support ui-select control?, here is my plunk http://plnkr.co/edit/6IApfRtmXqrzOlpQH5cM?p=preview

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.