AngularJS custom form validation

Angular achieved type (text, number, url, email , date, radio, checkbox) most commonly used form controls HTML5, implements as many instructions verification (required, pattern, minlength, maxlength , min, max) .
In the custom command, we can add our authentication method to ngModelController of $ validators objects. To achieve this controller object, we need requirengModel instruction.
Method on each object receives $ validators and viewValue modelValue two values as parameters. After returning a value (true, false) authentication method in your bindings, Angular calls $ setValidity method internally. Verification value will change every time the input box value change ($ setViewValue is called) or in the model. Verification occurs after the $ parsers and $ formatters run successfully, verify that items are not passed as ngModelController. $ Error attributes stored.
In addition, this controller object, there is a $ asyncValidators object of verification if you are asynchronous, you need to add additional verification on the object, for example, enter the phone number when user registration, we need to verify that the phone in the back-end whether the number has been registered, the authentication method must return a promise object and then call resolve lingering objects at the time of verification by calling reject failure, not yet completed the verification of asynchronous stored in ngModelController. $ pending in.

For example (note where the user objects, and only validated, and will bind the values ​​to the model):

<form name="register_form" ng-submit="save()">  
    <div class="form-group">  
        <label for="phoneNumber">  
            手机号(不能重复):  
        </label>  
        <input type="text" class="form-control" ng-model="user.phoneNumber" id="phoneNumber" name="phoneNumber" required phone>  
    </div>  
    <div class="form-group">  
        <label for="username">  
            用户名(必须大于五位):  
        </label>  
        <input type="text" class="form-control" ng-model="user.username" id="username" required username>  
    </div>  
    <button class="btn btn-block btn-primary" type="submit">提交</button>  
</form>  
<h3>用户对象</h3>  
<pre>  
    {{ user | json }}  
</pre>  
'use strict';  
angular.module('app', [])  
  
.directive('phone', function ($q, $http) {  
    return {  
        require: 'ngModel',  
        link: function (scope, ele, attrs, ctrl) {  
            ctrl.$asyncValidators.phone = function (modelValue, viewValue) {  
                var d = $q.defer();  
                $http.get('phone.json')  
                .success(function (phoneList) {  
                    if (phoneList.indexOf(parseInt(modelValue)) >= 0) {  
                        d.reject();  
                    } else {  
                        d.resolve();  
                    }  
                });  
                return d.promise;  
            }  
        }  
    }  
})  
  
.directive('username', function ($q, $http) {  
    return {  
        require: 'ngModel',  
        link: function (scope, ele, attrs, ctrl) {  
            ctrl.$validators.username = function (modelValue, viewValue) {  
                if (modelValue) {  
                    return modelValue.length > 5 ? true : false;  
                };  
                return false;  
            }  
        }  
    }  
})  
[  
    13758262732,  
    15658898520,  
    13628389818,  
    18976176895,  
    13518077986  
]  

effect:
1464605246_4922.gif

Following a complete user registration form validation:
HTML:

<form name="register_form" novalidate>  
            <div class="form-group">  
                <label for="username">用户名:</label>  
  
                <!-- ng-pattern="/PATTERN/"确保输入项符合正则 -->  
                <input type="text" id="username" ng-model="user.username" class="form-control" name="username" required ng-pattern="/^[^#]*$/">  
                <span class="glyphicon glyphicon-ok right" ng-show="register_form.username.$valid"></span>  
            </div>  
            <div class="alert alert-danger" ng-show="register_form.username.$error.pattern">  
                <strong>请注意!</strong>  
                用户名不能带#号。  
            </div>  
            <div class="alert alert-danger" ng-show="register_form.username.$error.required && register_form.username.$touched">  
                <strong>请注意!</strong>  
                用户名不能为空。  
            </div>  
            <div class="form-group">  
                <label for="_password">密码:</label>  
  
                <!-- ng-minlength="num"让密码不能小于最小长度 -->  
                <input type="password" id="_password" ng-model="data._password" class="form-control" required ng-minlength="8" name="_password">  
                <span class="glyphicon glyphicon-ok right" ng-show="register_form._password.$valid"></span>  
            </div>  
            <div class="alert alert-danger" ng-show="register_form._password.$error.minlength && register_form._password.$touched">  
                <strong>请注意!</strong>  
                密码长度不能少于八位。  
            </div>  
            <div class="alert alert-danger" ng-show="register_form._password.$error.required && register_form._password.$touched">  
                <strong>请注意!</strong>  
                密码不能为空。  
            </div>  
            <div class="form-group">  
                <label for="password">确认密码:</label>  
                <input type="password" id="password" ng-model="user.password" class="form-control" name="password" required pwd-repeat>  
                <span class="glyphicon glyphicon-ok right" ng-show="register_form.password.$valid"></span>  
            </div>  
            <div class="alert alert-danger" ng-show="register_form.password.$error.pwdRepeat && register_form.password.$touched">  
                <strong>请注意!</strong>  
                两次输入的密码不相同。  
            </div>  
            <div class="alert alert-danger" ng-show="register_form.password.$error.required && register_form.password.$touched">  
                <strong>请注意!</strong>  
                请再次输入密码。  
            </div>  
            <div class="form-group">  
                <label for="phone">手机号:</label>  
                <div class="row">  
                    <div class="col-sm-10">  
                        <input type="num" id="phone" ng-model="user.phone" name="phone" class="form-control" required ng-minlength="11" ng-maxlength="11" phone>  
                    </div>  
                    <div class="col-sm-2">  
                        <button class="btn btn-default" type="button" ng-disabled="register_form.phone.$invalid">发送验证码</button>  
                    </div>  
                </div>  
                <span class="glyphicon glyphicon-ok right" ng-show="register_form.phone.$valid"></span>  
            </div>  
            <div class="alert alert-danger" ng-show="register_form.phone.$error.phone">  
                <strong>请注意!</strong>  
                该手机号已注册过,可直接登录。  
            </div>  
            <div class="alert alert-danger" ng-show="register_form.phone.$touched && !register_form.phone.$error.phone && (register_form.phone.$error.required || register_form.phone.$error.minlength || register_form.phone.$error.maxlength)">  
                <strong>请注意!</strong>  
                请输入正确的手机号。  
            </div>  
            <div class="form-group">  
                <label for="code">验证码:</label>  
                <input type="text" id="code" ng-model="user.code" class="form-control" name="code" required>  
                <span class="glyphicon glyphicon-ok right" ng-show="register_form.code.$valid"></span>  
            </div>  
  
            <!-- 在表单不合法时禁用提交按钮 -->  
            <button class="btn btn-block btn-primary" type="submit" ng-disabled="register_form.$invalid" ng-click="save()">提交</button>  
        </form>  
'use strict';  
angular.module('app', [])  
.controller('myCtrl', function ($scope) {  
    $scope.data = {};  
    $scope.save = function () {  
        alert('保存成功!')  
    }  
})  
  
// 判断手机号是否重复  
.directive('phone', function ($q, $http) {  
    return {  
        require: 'ngModel',  
        link: function (scope, ele, attrs, ctrl) {  
            ctrl.$asyncValidators.phone = function (modelValue, viewValue) {  
                var d = $q.defer();  
                $http.get('phone.json')  
                .success(function (phoneList) {  
                    if (phoneList.indexOf(parseInt(modelValue)) >= 0) {  
                        d.reject();  
                    } else {  
                        d.resolve();  
                    }  
                });  
                return d.promise;  
            }  
        }  
    }  
})  
  
// 验证两次输入的密码是否相同的自定义验证  
.directive('pwdRepeat', function () {  
    return {  
        require: 'ngModel',  
        link: function (scope, ele, attrs, ctrl) {  
  
            ctrl.$validators.pwdRepeat = function (modelValue) {  
  
                // 当值为空时,通过验证,因为有required  
                if (ctrl.$isEmpty(modelValue)) {  
                    return true;  
                }  
  
                return modelValue === scope.data._password ? true : false;  
            }  
        }  
    }  
})  
form-group {  
    position: relative;  
}  
.right {  
    position: absolute;  
    right: 10px;  
    top: 34px; 
    color: green';
} 

1464666664_5384.gif

Guess you like

Origin www.cnblogs.com/homehtml/p/12634116.html