SoFunction
Updated on 2025-03-10

AngularJS implements form validation

Although I am not a front-end programmer, I understand how important it is to do a good job of verification on the front-end.

Because in this way, the backend can take a more breath, and compared with the backend, the frontend can indeed improve the user's sense of happiness.

AngularJS provides a very convenient form verification function, record it here.

First start with the following code

Copy the codeThe code is as follows:

<form ng-app="myApp" ng-controller="validationController" name="mainForm" novalidate>
    <p>Email:
        <input type="email" name="email" ng-model="email" required>
        <span style="color:red" ng-show=".$dirty && .$invalid">
            <span ng-show=".$">Email is required.</span>
            <span ng-show=".$">Invalid email address.</span>
        </span>
    </p>
    <p>
        <input type="submit" ng-disabled="mainForm.$invalid">
    </p>
</form>
<script>
('myApp',[])
.controller('validationController', ['$scope',function($scope) {
    $ = 'Kavlez';
    $ = 'sweet_dreams@';
}]);
</script>

Some verification options for input tags are usually used with HTML5 tags.

Required

<input type="text" required />
length

Use the directive ng-minlength/ng-maxlength

<input type="text" ng-minlength="5" />
Specific format
For example, email, URL, and number, just set the type to the corresponding type, for example:

Copy the codeThe code is as follows:

<input type="email" name="email" ng-model="" />
<input type="number" name="age" ng-model="" />
<input type="url" name="homepage" ng-model="user.facebook_url" />

Pattern matching

Use the directive ng-pattern, for example:

Copy the codeThe code is as follows:

<input type="text" ng-pattern="[a-z]" />

Form properties, these properties make it easier to operate on forms

pristine/dirty
Indicates whether it has been modified, e.g.

Copy the codeThe code is as follows:

<form name="mainForm" ng-controller="orderController">
<input type="email" name="userEmail" ng-model="myEmail" />
    {{.$pristine}}
    {{.$dirty}}
</form>

Accessed in .$pristine mode, input must have an ng-model declaration.

Copy the codeThe code is as follows:

valid/invalid

Indicates whether it passes verification.

Copy the codeThe code is as follows:

$error

Form verification information, and the corresponding information is returned if the verification fails.

AngularJS provides css class accordingly for form status

Copy the codeThe code is as follows:

.ng-pristine
.ng-dirty
.ng-valid
.ng-invalid

For example, let verification pass green and fail red:

Copy the codeThe code is as follows:

-valid {
    color: green;
}
-invalid {
    color: green;
}

In the example given, just one email verification is written so much. If you add a few fields, add a few different prompts, and add a few events, the code will become messy.

In fact, it is not recommended to do this, we have a better way.
Just use

First of all, don't forget these two steps

Copy the codeThe code is as follows:

<script src=""></script>
('myApp', ['ngMessages'])

OK, first replace those duplicates with ng-messages and ng-message, and the above example becomes:

Copy the codeThe code is as follows:

<form ng-controller="validationController" name="mainForm" >
    <p>Email:
        <input
        type="email" name="email" ng-model="myEmail" ng-minlength="3" ng-maxlength="50" required />
        <div style="color:red" ng-messages=".$error" ng-messages-multiple>
            <p class="error" ng-message="required">Email is required.</p>
            <p class="error" ng-message="email">Invalid email address.</p>
            <p class="error" ng-message="minlength">min length 10</p>
            <p class="error" ng-message="maxlength">max length 50</p>
        </div>
    </p>
    <p>
        <input type="submit" ng-disabled="mainForm.$invalid" />
    </p>
</form>

There is no change in function, just the duplicate code is removed.
Pay attention to distinguishing between ng-messasges and ng-messages. Does it feel a bit like with()? The ng-messages-multiple behind it is used to make multiple prompts appear at the same time.

But this is still not good enough. Even if the content in ng-message is omitted, there will still be duplication when required verification exists in multiple fields.
Moreover, there will be more and more repeated verification prompts when forms on different pages involve the same content.
To solve this problem, we can use the ng-messages-include directive.
This directive is used to reference templates, for example, the above example becomes:

Copy the codeThe code is as follows:

<form ng-controller="validationController" name="mainForm" >
    <p>Email:
        <input
        type="email" name="email" ng-model="myEmail" ng-minlength="3" ng-maxlength="50" required />
        <div style="color:red" ng-messages=".$error" ng-messages-multiple ng-messages-include="validateTemplate/">
        </div>
    </p>
    <p>
        <input type="submit" ng-disabled="mainForm.$invalid" />
    </p>
</form>

It's not complicated, let's add something.
In order to make the prompts more friendly (?), we try to achieve the effect of prompts appearing after the cursor leaves.
At this time, it will be much more convenient to use directives. Here we first involve some information related to the instructions.

Run it first and then talk about it:

Copy the codeThe code is as follows:

var myApp = ('myApp',[])
    .controller('validationController', ['$scope',function($scope) {
        $ = 'Kavlez';
        $ = 'sweet_dreams@';
    }])
    .directive('hintOnBlur', [function() {
        return {
            require: 'ngModel',
            link: function(scope, element, attrs, ctrl) {
                = false;
                ('focus', function(evt) {
                    scope.$apply(function() { = true;});
                }).bind('blur', function(evt) {
                    scope.$apply(function() { = false;});
                });
            }
        }
    }]);

Here we use focused to determine whether the cursor is on a certain property. When the focus or blur event occurs on an object using the hintOnBlur directive, the state of focus changed.

The form will be changed as follows:

Copy the codeThe code is as follows:

<form ng-controller="validationController" name="mainForm" >
    <p>Email:
        <input type="email" name="email" ng-model="myEmail" ng-minlength="3" ng-maxlength="50" required hint-on-blur />
        <div style="color:red" ng-messages=".$error" ng-show="!" ng-messages-multiple ng-messages-include="validateTemplate/">
        </div>
    </p>
    <p>
        <input type="submit" ng-disabled="mainForm.$invalid" />
    </p>
</form>

Add the judgment of focused in ng-show, and a prompt appears when false.

It looks like that now.
Customize verification methods and validity, which also uses directives.
Verify that the email you filled in has occupied. Here is a simple simulation:

Copy the codeThe code is as follows:

.directive('isAlreadyTaken', function() {
    return {
        require: 'ngModel',
        link: function(scope, ele, attrs, ctrl) {
            ctrl.$(function(val) {
                ctrl.$setValidity('emailAvailable', false);
                var emailTable = [
                    'K@',
                    'a@',
                    'v@',
                    'l@',
                    'e@',
                    'z@'];
                for (var i=0;i<;i+=1)
                    if(val==emailTable[i])
                        return;
                ctrl.$setValidity('emailAvailable', true);
                return val;
            })
        }
    }
})

Add the is-already-taken attribute to the Input element and add another ng-message:

Copy the codeThe code is as follows:

<p class="error" ng-message="emailAvailable">Already taken! try other email addresses!</p>