整理项目中用到的angularjs--form表单验证

form表单验证概述

  • novalidate -- 屏蔽浏览器对表单的默认验证行为

  • ng-model -- 绑定的数据

  • ng-required -- 是否必填(可以控制是否是不填校验)

  • required -- 必填(页面加载的时候就会自动验证 == true)

  • ng-minlength -- 最小长度

  • ng-maxlength -- 最大长度

  • ng-pattern -- 匹配模式(正则)

  • email -- 邮箱

  • url -- 网址

  • number -- 数字

  • ng-change -- 值变化的回调

在表单中控制变量

  • formName.inputField.$pristine 字段是否 未更改

  • formName.inputField.$dirty 字段是否 更改

  • formName.inputField.$valid 字段是否 有效

  • formName.inputField.$invalid 字段是否 无效

  • formName.inputField.$error 字段 错误信息

一些有用的CSS样式

  • ng-valid //有效时的样式名
  • ng-invalid //无效时的样式名
  • ng-pristine //未更改的样式名
  • ng-dirty //更改后的样式名
  • ng-submitted //提交后的样式名.当用户试图提交表单时,可以在作用域中捕获到一个submitted值,然后对表单内容进行验证并显示错误信息

  例如:

      input.ng-invalid {
        border: 1px solid red;
      }
      input.ng-valid {  
        border: 1px solid green;
      }

form表单示例

 <!--注册表单-->
    <form class="zhucezhuti" id="myForm" role="form" ng-app="validate" ng-controller="validateCtrl" name="myForm" ng-submit="submitFormRegiter(myForm.$valid,'Regiter','/UserCenter/UpdateUserMessage')" novalidate>
        <div class="mb-15 distab marcenter">
            <input class="querenyong" type="email" id="UserEmail" data-value="1" name="UserEmail" placeholder="电子邮箱(用户名)" ng-model="UserEmail" required>
            <span class="errorSty" ng-show="myForm.UserEmail.$dirty && myForm.UserEmail.$invalid && myForm.submitted">
                <span ng-show="myForm.UserEmail.$error.required">*请输入邮箱</span>
                <span ng-show="myForm.UserEmail.$error.email">*非法的邮箱地址。</span>
            </span>
            <span class="eSsuccess"></span>
        </div>
        <div class="mb-15 distab marcenter">
            <div class="distab">
                <input class="yanzhengma" type="number" id="emailYZM" name="yzm" placeholder="邮箱验证码" ng-model="yzm" required>
                <input class="huoquyan" type="button" id="btn" value="获取邮箱验证码" ng-disabled="myForm.UserEmail.$invalid" onclick="time(this, 'SendMailMessage')" />
            </div>
            <span class="errorSty" ng-show="myForm.yzm.$dirty && myForm.yzm.$invalid && myForm.submitted">
                <span ng-show="myForm.yzm.$error.required">*请输入验证码。</span>
                <span ng-show="myForm.yzm.$error.number">*请输入正确的验证码。</span>
            </span>
        </div>
        <div class="mb-15 distab marcenter">
            <input class="querenyong" type="password" name="password" id="password" placeholder="密码(6-16个字符组成,区分大小写)" ng-model="password" ng-minlength="6" ng-maxlength="16" required>
            <span class="errorSty" ng-show="myForm.password.$dirty && myForm.password.$invalid && myForm.submitted">
                <span ng-show="myForm.password.$error.required">*密码是必须的。</span>
                <span ng-show="myForm.password.$error.minlength">*密码不少于6位。</span>
                <span ng-show="myForm.password.$error.maxlength">*密码不多于16位。</span>
            </span>
        </div>
        <div class="mb-15 distab marcenter">
            <input class="querenyong" type="password" name="confirmPassword" id="confirmPassword" placeholder="确认密码" ng-model="confirmPassword" pw-check="password" required>
            <span class="errorSty" ng-show="myForm.confirmPassword.$dirty && myForm.confirmPassword.$invalid && myForm.submitted">
                <span ng-show="myForm.confirmPassword.$error.required">*确认密码必填。</span>
                <span ng-show="!myForm.confirmPassword.$pristine && myForm.confirmPassword.$invalid">*预设密码和确认密码不一致。</span>
            </span>
        </div>
        <div class="tiaokuan mb-15">
            <input class="fuxuan" ng-model="Iagree" type="checkbox" required>&nbsp;&nbsp;<font class="yuedu">请务必仔细阅读并同意&nbsp;<a href="javascript:void(0)" onclick="showTanc('tanc','closethis')">网站使用条款</a>&nbsp;和&nbsp;<a href="javascript:void(0)" onclick="showTanc('tanc1','closethis')">电子金融交易使用条款&nbsp;</a></font>

            <span class="errorSty" ng-show="myForm.Iagree.$invalid && myForm.submitted">
                <span ng-show="myForm.Iagree.$error.required">*您未同意条款。</span>
            </span>
        </div>
        <input class="zhucedenglu" type="submit" value="注册" ng-disabled="!myForm.$dirty">
    </form>
HTML代码
var app = angular.module('validate', []);
app.controller('validateCtrl', function ($scope) {

    //仅当submitted设置为true时,容纳错误信息的div才会展示出来(即提交表单时显示相应错误信息)
    $scope.submitted = false; 
    
    $scope.submitFormRegiter = function (isValid, action, nextaction) {
        if (!isValid) {
           // alert('验证失败');
            $scope.myForm.submitted = true;
        } else {
            $.get(action, { UserEmail: $("#UserEmail").val(), messageCode: $("#messageCode").val(), UserPassWord: $("#password").val() }, function (result) {
                if (result.ReState == true) {
                    window.location.href = nextaction;
                } else {
                    alert("操作失败!");//完善信息页面没有返回提示信息。根据ReState显示相应提示
                }
            });
        }
    };
})
JS代码

如果想保留实时错误提示的体验,可以在用户从某个输入字段失焦后提示错误信息:(添加一个自定义指令)

html代码
<input ng-class="{error: signup_form.name.$dirty && signup_form.name.$invalid}" 
    type="text" 
    placeholder="Name" 
    name="name" 
    ng-model="signup.name" 
    ng-minlength="3" 
    ng-maxlength="20" required ng-focus /> 


js代码
app.directive('ngFocus', [function() { 
    var FOCUS_CLASS = "ng-focused"; 
    return { 
        restrict: 'A', 
        require: 'ngModel', 
        link: function(scope, element, attrs, ctrl) { 
            ctrl.$focused = false; 
            element.bind('focus', function(evt) { 
                element.addClass(FOCUS_CLASS); 
                scope.$apply(function() { 
                    ctrl.$focused = true; 
                }); 
            }).bind('blur', function(evt) { 
                element.removeClass(FOCUS_CLASS); 
                scope.$apply(function() { 
                    ctrl.$focused = false; 
                }); 
            }); 
        } 
    }; 
}]); 

ngFocus指令给表单输入字段的blur和focus添加了对应的行为,添加了一个名为ng-focused的类,并将$focused的值设置为true。接下来,可以根据表单是否具有焦点来展示独立的错误信息。如下所示:

<div class="error" ng-show="signup_form.name.$dirty && signup_form.name.$invalid && !signup_form.name.$focused"> 
View Code

在发布的Angularjs 1.3中,Angularjs核心做了一个升级。它不再需要基于一个详细的表达式状态创建元素显示或隐藏。从1.3开始,Angularjs中新增了一个ngMessages指令

  1. 安装:<script type="text/javascript" src="bower_components/angular-messages/angular-messages.js"></script>
  2. 告诉angularjs将ngMessage作为应用程序的依赖模块引入:angular.module('myApp',['ngMessages']);
  3. 开始使用:<div class="error" ng-messages="signup_form.name.$error" ng-messages-include="templates/errors.html" ng-messages-multiple>
  4. 如果想要更新这个实现同时显示所有的错误,只需在ng-message指令旁使用ng-messages-multiple属性即可
  5. <!-- templates/errors.html内容 -->
    1. <div ng-message="required">This field is required</div>
    2. <div ng-message="minlength">The field must be at least 3 characters</div>
    3. <div ng-message="maxlength">The field cannot be longer than 20 characters</div>
  6. 为不同的字段自定义错误信息,可以在这个指令内简单地插入一个自定义错误信息。由于ngMessages涉及ngMessages容器中错误列表的顺序,可以通过在这个指令中列出自定义错误信息的方式覆盖它们

ngMessages示例

<form name="signup_form" novalidate ng-submit="signupForm()" ng-controller="signupController" 
ensure-unique="/api/checkUsername.json"> 
    <label> 
        Your name 
    </label> 
    <input type="text" placeholder="Username" name="username" ng-model="signup.username" 
    ng-minlength=3 ng-maxlength=20 required /> 
    <div class="error" ng-messages="signup_form.username.$error"> 
        <div ng-message="required"> 
            Make sure you enter your username 
        </div> 
        <div ng-message="checkingAvailability"> 
            Checking... 
        </div> 
        <div ng-message="usernameAvailablity"> 
            The username has already been taken. Please choose another 
        </div> 
    </div> 
    <button type="submit"> 
        Submit 
    </button> 
</form> 
在这个用法中,我们检查了错误信息的自定义属性。为了添加自定义错误信息,将会把他们应用到自定义ensureUnique指令的ngModel中
app.directive('ensureUnique', function($http) { 
    return { 
        require: 'ngModel', 
        link: function(scope, ele, attrs, ctrl) { 
            var url = attrs.ensureUnique; 
            ctrl.$parsers.push(function(val) { 
                if (!val || val.length === 0) { 
                    return; 
                } 
                ngModel.$setValidity('checkingAvailability', true); 
                ngModel.$setValidity('usernameAvailablity', false); 
                $http({ 
                    method: 'GET', 
                    url: url, 
                    params: { 
                        username: val 
                    } 
                }).success(function() { 
                    ngModel 
                        .$setValidity('checkingAvailability', false); 
                    ngModel 
                        .$setValidity('usernameAvailablity', true); 
                })['catch'](function() { 
                    ngModel 
                        .$setValidity('checkingAvailability', false); 
                    ngModel 
                        .$setValidity('usernameAvailablity', false); 
                }); 
                return val; 
            }) 
        } 
    } 
}); 
ngMessages示例
原文地址:https://www.cnblogs.com/ywang/p/5627155.html