美文网首页
AngularJs 表单字段合法性校验

AngularJs 表单字段合法性校验

作者: TryCatch菌 | 来源:发表于2019-08-26 00:36 被阅读0次

    AngularJs 表单字段合法性校验

    基于AngularJS入门与进阶(江荣波 著)这本书的笔记

    AngularJS 1.x的demo

    AngularJS1.x和Angular2,4,5是不一样的两个东西,构建方式,语法,都很多不同

    参考文章:https://www.oschina.net/translate/angularjs-form-validation


    在AngularJs要使用自带的表单验证,只需要在页面定义一个<form>标签,然后定义表单,再使用ng-model进行数据的双向绑定就可以了。
    CSS样式与状态对应的属性关系

    CSS样式 状态属性 描述
    ng-valid $valid 表单输入合法
    ng-invalid $invalid 表单输入不合法
    ng-pristine $pristine 表单元素未被使用
    ng-dirty $dirty 表单元素被使用
    ng-touched $touched 元素获取焦点
    ng-untouched $untouched 元素失去焦点
    ng-empty $empty 元素内容为空

    AngularJs表单常用校验相关属性和指令

    校验名 指令名 示例
    必填 required <input type="text" required>
    最小长度 ng-minlength="{number}" <input type="text" ng-minlength="10">
    最大长度 ng-maxlength="{number}" <input type="text" ng-maxlength="10">
    正则匹配 ng-pattern="/pattern/" <input type="text" ng-pattern="[0-9]">
    邮箱格式 type = "email" <input type="email" ng-model="user.email">
    数字格式 type = "number" <input type="number" ng-model="user.age">
    网址格式 type = "url" <input type="url" ng-model="user.url">

    首先假设有个注册页面的场景,有个用户注册页面

    • 用户名必填
    • 密码只能是数字或者英文字母
    • 密码长度8到16位
    • 邮箱必须格式合法

    ng-showng-messages指令
    表单验证如果不通过,我们通常需要给用户提示出对应的错误信息,ng-show指令可以在ng-show="false"的时候控制显示和隐藏,true为显示,false为隐藏,上面表格也说了可以通过$invalid获取到当前文本框是否合法的boolean
    如果是单条错误提示可以用ng-show实现,有时候我们一个文本框有过多个验证,需要提示,可以用ng-messages指令,当检测到不合法的时候,会顺序显示第一条不合法的提示信息,如果需要使用ng-message指令,必须在module中引入ngMessages,并且页面引入angular-messages.js

    一个简单控制器 app.js

    var formApp = angular.module("formApp",["ngMessages"]);
    formApp.controller("formController",function ($scope,$log) {
        $scope.submitValid = function (isValid) {
            if(!isValid) {
                $('#showMsg').text("验证不通过,请检查!");
                $('#showMsgDiv').modal();
            }
        }
    });
    

    demo页面 index.html

    <!DOCTYPE html>
    <html lang="en" ng-app="formApp">
    <head>
        <meta charset="UTF-8">
        <title>表单验证</title>
        <link rel="stylesheet" href="/bootstrap-3.3.7/dist/css/bootstrap.css">
        <link rel="stylesheet" href="/bootstrap-3.3.7/dist/css/bootstrap-theme.min.css">
        <script  src="/lib/angular/angular.js"></script>
        <script  src="/lib/angular-messages/angular-messages.js"></script>
        <script  src="../../js/jquery-1.9.1/jquery.js"></script>
        <script src="/bootstrap-3.3.7/dist/js/bootstrap.js"></script>
        <script src="app.js"></script>
        <style>
            body
            {   padding-top:30px;
                padding-left: 600px;
            }
        </style>
    </head>
    <body ng-controller="formController">
    <di class = 'page-header'><h3>AngularJs 表单验证</h3></di>
    <!-- novalidate 禁用自带的验证规则-->
    <form name ='userForm' novalidate ng-submit="submitValid(userForm.$valid)" style="width: 300px;">
        <div class="form-group"  style="height: 70px;">
            <label>用户名</label>
            <input type="text" class="form-control" name="userName" ng-model="userName" required>
            <!--必填单纯判断会在页面加载的时候就显示错误提示,可以先判断表单是否未使用$pristine 可以避免页面加载进来就提示错误-->
            <span ng-show="userForm.userName.$invalid && !userForm.userName.$pristine" class="help-block">必填项</span>
        </div>
    
        <div class="form-group" style="height: 70px;">
            <label>密码</label>
            <input type="text" class="form-control" name="password" ng-model="password"
                    ng-pattern="/^[A-Za-z0-9]+$/" ng-minlength="8" ng-maxlength="16">
            <!--这里有2个验证规则,第一个是只能是数字或者字母,第二个是长度要在8-16位 使用ng-messages优先提示格式,然后提示长度-->
            <div ng-messages="userForm.password.$error" >
                <span ng-message="pattern">密码只能是数字或英文字母</span>
                <span ng-message="minlength">密码长度最短8位</span>
                <span ng-message="maxlength">密码长度最长16位</span>
            </div>
        </div>
    
        <div class="form-group" style="height: 70px;">
            <label>邮箱</label>
            <input type="email" class="form-control" name="email" ng-model="email" >
            <span ng-show="userForm.email.$invalid  && !userForm.email.$pristine" class="help-block">邮箱格式错误</span>
        </div>
    
        <button type="submit" class="btn btn-primary">提交</button>
    </form>
    <!-- 模态弹出窗 -->
    <div class="modal fade" id="showMsgDiv">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title">提示信息</h4>
                </div>
                <div class="modal-body">
                    <p id="showMsg"></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <!--<button type="button" class="btn btn-primary">保存</button>-->
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
    </body>
    </html>
    
    20190825_214359[00-00-00--00-00-21].gif
    失去焦点时验证

    从页面验证可以看出所有验证都是生效的了的,也按照我们的预期在验证,基于AngularJs的数据双向绑定,我们发现我们所有的验证都是及时生效的,这在大多数情况下是期望的,不过在注册这种情况下,我们不期望在用户输入的过程中就提示,期望是文本框失去焦点或者提交的时候验证。

    ng-model-optionsng-blurng-focus
    如果要达到获取焦点或失去焦点的时候验证的方式比较多,这里举例两种,ng-model-optionsng-blurng-focus

    首先我们做了个变量change,在通过ng-blurng-focus在获取或失去焦点的时候改变这个值,让ng-show指令中的表达式在失去焦点的时候才成立往下验证
    对像中的blur,给对象添加一个判断当前输入框是否失去焦点的属性 userForm.email.$error.blur,再用input的事件ng-focus,ng-blur来动态改变这个值。

        <div class="form-group" style="height: 70px;">
            <label>邮箱</label>
            <input type="email" class="form-control" name="email" ng-model="email"
                    ng-blur="change=true" ng-focus="change=false">
            <span ng-show="change && userForm.email.$invalid  && !userForm.email.$pristine" class="help-block">邮箱格式错误</span>
        </div>
    

    还可以用ng-model-option,在默认情况下,任何内容的改变将触发表单验证和model的更新。ngModelOptions指令绑定到一个事件集合中来重写触发的时间,例如:ng-model-options="{ updateOn: 'blur' }" 将会在控件失去焦点后执行表单验证和更新Model。你可以使用空格来分割多个事件的触发验证和更新的时间。例如:ng-model-options="{ updateOn: 'mousedown blur' }"。

        <div class="form-group" style="height: 70px;">
            <label>密码</label>
            <input type="text" class="form-control" name="password" ng-model="password"
                    ng-pattern="/^[A-Za-z0-9]+$/" ng-minlength="8" ng-maxlength="16"
                    ng-model-options="{ updateOn: 'blur' }">
            <!--这里有2个验证规则,第一个是只能是数字或者字母,第二个是长度要在8-16位 使用ng-messages优先提示格式,然后提示长度-->
            <div ng-messages="userForm.password.$error" >
                <span ng-message="pattern" class="help-block">密码只能是数字或英文字母</span>
                <span ng-message="minlength" class="help-block">密码长度最短8位</span>
                <span ng-message="maxlength" class="help-block">密码长度最长16位</span>
            </div>
        </div>
    

    ng-class动态改变文本框样式
    在验证的时候我们还期望错误的文本框改变颜色,ng-class 允许我们基于一个表达式添加类。因为我们使用了 Bootstrap, 我们将就使用它们提供的类(has-error)

        <div class="form-group"  style="height: 70px;" ng-class="{'has-error' : userForm.userName.$invalid && !userForm.userName.$pristine}">
            <label>用户名</label>
            <input type="text" class="form-control" name="userName" ng-model="userName" required
                    ng-model-options="{ updateOn: 'blur' }">
            <!--必填单纯判断会在页面加载的时候就显示错误提示,可以先判断表单是否未使用$pristine 可以避免页面加载进来就提示错误-->
            <span ng-show="userForm.userName.$invalid && !userForm.userName.$pristine" class="help-block">必填项</span>
        </div>
    
        <div class="form-group" style="height: 70px;" ng-class="{'has-error' : userForm.password.$invalid && !userForm.password.$pristine}">
            <label>密码</label>
            <input type="text" class="form-control" name="password" ng-model="password"
                    ng-pattern="/^[A-Za-z0-9]+$/" ng-minlength="8" ng-maxlength="16"
                    ng-model-options="{ updateOn: 'blur' }">
            <!--这里有2个验证规则,第一个是只能是数字或者字母,第二个是长度要在8-16位 使用ng-messages优先提示格式,然后提示长度-->
            <div ng-messages="userForm.password.$error" >
                <span ng-message="pattern" class="help-block">密码只能是数字或英文字母</span>
                <span ng-message="minlength" class="help-block">密码长度最短8位</span>
                <span ng-message="maxlength" class="help-block">密码长度最长16位</span>
            </div>
        </div>
    

    下面是完整的html,app.js没做改变

    <!DOCTYPE html>
    <html lang="en" ng-app="formApp">
    <head>
        <meta charset="UTF-8">
        <title>表单验证</title>
        <link rel="stylesheet" href="/bootstrap-3.3.7/dist/css/bootstrap.css">
        <link rel="stylesheet" href="/bootstrap-3.3.7/dist/css/bootstrap-theme.min.css">
        <script  src="/lib/angular/angular.js"></script>
        <script  src="/lib/angular-messages/angular-messages.js"></script>
        <script  src="../../js/jquery-1.9.1/jquery.js"></script>
        <script src="/bootstrap-3.3.7/dist/js/bootstrap.js"></script>
        <script src="app.js"></script>
        <style>
            body
            {   padding-top:30px;
                padding-left: 600px;
            }
        </style>
    </head>
    <body ng-controller="formController">
    <di class = 'page-header'><h3>AngularJs 表单验证</h3></di>
    <!-- novalidate 禁用自带的验证规则-->
    <form name ='userForm' novalidate ng-submit="submitValid(userForm.$valid)" style="width: 300px;">
        <div class="form-group"  style="height: 70px;" ng-class="{'has-error' : userForm.userName.$invalid && !userForm.userName.$pristine}">
            <label>用户名</label>
            <input type="text" class="form-control" name="userName" ng-model="userName" required
                    ng-model-options="{ updateOn: 'blur' }">
            <!--必填单纯判断会在页面加载的时候就显示错误提示,可以先判断表单是否未使用$pristine 可以避免页面加载进来就提示错误-->
            <span ng-show="userForm.userName.$invalid && !userForm.userName.$pristine" class="help-block">必填项</span>
        </div>
    
        <div class="form-group" style="height: 70px;" ng-class="{'has-error' : userForm.password.$invalid && !userForm.password.$pristine}">
            <label>密码</label>
            <input type="text" class="form-control" name="password" ng-model="password"
                    ng-pattern="/^[A-Za-z0-9]+$/" ng-minlength="8" ng-maxlength="16"
                    ng-model-options="{ updateOn: 'blur' }">
            <!--这里有2个验证规则,第一个是只能是数字或者字母,第二个是长度要在8-16位 使用ng-messages优先提示格式,然后提示长度-->
            <div ng-messages="userForm.password.$error" >
                <span ng-message="pattern" class="help-block">密码只能是数字或英文字母</span>
                <span ng-message="minlength" class="help-block">密码长度最短8位</span>
                <span ng-message="maxlength" class="help-block">密码长度最长16位</span>
            </div>
        </div>
    
        <div class="form-group" style="height: 70px;" ng-class="{'has-error' : change && userForm.email.$invalid  && !userForm.email.$pristine}">
            <label>邮箱</label>
            <input type="email" class="form-control" name="email" ng-model="email"
                    ng-blur="change=true" ng-focus="change=false">
            <span ng-show="change && userForm.email.$invalid  && !userForm.email.$pristine" class="help-block">邮箱格式错误</span>
        </div>
        <button type="submit" class="btn btn-primary">提交</button>
    </form>
    <!-- 模态弹出窗 -->
    <div class="modal fade" id="showMsgDiv">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title">提示信息</h4>
                </div>
                <div class="modal-body">
                    <p id="showMsg"></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <!--<button type="button" class="btn btn-primary">保存</button>-->
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
    </body>
    </html>
    
    20190826_001900[00-00-00--00-00-15].gif
    提交时验证

    提交时验证的原理也是通过angularJS的双向数据绑定原理,这里因为做了判断文本框是否使用,修改提交的验证方法,在提交的时候把所有文本框设置为已经使用,然后还做了个全局变量,是否提交,控制ng-show和ng-messages 判断表达式

    app.js

    var formApp = angular.module("formApp",["ngMessages"]);
    formApp.controller("formController",function ($scope,$log) {
        // 失去焦点验证变量
        $scope.changeFlagBon = false;
        // 提交变量
        $scope.isSubmit = false;
        
        // form 提交时的方法
        $scope.submitValid = function (isValid,userForm) {
            if(!isValid) {
                // 提交的时候所有的输入框都设置为已经使用
                userForm.userName.$pristine =false;
                userForm.password.$pristine =false;
                userForm.email.$pristine =false;
                $scope.changeFlagBon = true;
                
                // 处理更详细的验证
    
                // 提交变量设置为已经提交
                $scope.isSubmit = true;
    
                $('#showMsg').text("验证不通过,请检查!");
                $('#showMsgDiv').modal();
            }else {
                // 处理提交逻辑
            }
        }
        
        // ng-blur  ng-focus  获取焦点,失去焦点方法
        $scope.changeFlag = function (flag) {
            $scope.changeFlagBon = flag;
        }
    });
    
    
    

    index.html

    <!DOCTYPE html>
    <html lang="en" ng-app="formApp">
    <head>
        <meta charset="UTF-8">
        <title>表单验证</title>
        <link rel="stylesheet" href="/bootstrap-3.3.7/dist/css/bootstrap.css">
        <link rel="stylesheet" href="/bootstrap-3.3.7/dist/css/bootstrap-theme.min.css">
        <script  src="/lib/angular/angular.js"></script>
        <script  src="/lib/angular-messages/angular-messages.js"></script>
        <script  src="../../js/jquery-1.9.1/jquery.js"></script>
        <script src="/bootstrap-3.3.7/dist/js/bootstrap.js"></script>
        <script src="app.js"></script>
        <style>
            body
            {   padding-top:30px;
                padding-left: 600px;
            }
        </style>
    </head>
    <body ng-controller="formController">
    <di class = 'page-header'><h3>AngularJs 表单验证</h3></di>
    <!-- novalidate 禁用自带的验证规则-->
    <form name ='userForm' novalidate ng-submit="submitValid(userForm.$valid,userForm)" style="width: 300px;">
        <div class="form-group"  style="height: 70px;" ng-class="{'has-error' : userForm.userName.$invalid && !userForm.userName.$pristine}">
            <label>用户名</label>
            <input type="text" class="form-control" name="userName" ng-model="userName" required
                    ng-model-options="{ updateOn: 'blur' }">
            <!--必填单纯判断会在页面加载的时候就显示错误提示,可以先判断表单是否未使用$pristine 可以避免页面加载进来就提示错误-->
            <span ng-show="userForm.userName.$invalid && !userForm.userName.$pristine" class="help-block">必填项</span>
        </div>
    
        <div class="form-group" style="height: 70px;" ng-class="{'has-error' :isSubmit && userForm.password.$invalid && !userForm.password.$pristine}">
            <label>密码</label>
            <input type="text" class="form-control" name="password" ng-model="password" required
                    ng-pattern="/^[A-Za-z0-9]+$/" ng-minlength="8" ng-maxlength="16"
                    ng-model-options="{ updateOn: 'blur' }">
            <!--这里有2个验证规则,第一个是只能是数字或者字母,第二个是长度要在8-16位 使用ng-messages优先提示格式,然后提示长度-->
            <div ng-messages="userForm.password.$error" ng-if="isSubmit">
                <span ng-message="pattern" class="help-block">密码只能是数字或英文字母</span>
                <span ng-message="minlength" class="help-block">密码长度最短8位</span>
                <span ng-message="maxlength" class="help-block">密码长度最长16位</span>
                <span ng-message="required" class="help-block">密码必填</span>
            </div>
        </div>
        <div class="form-group" style="height: 70px;" ng-class="{'has-error' : changeFlagBon && userForm.email.$invalid  && !userForm.email.$pristine}">
            <label>邮箱</label>
            <input type="email" class="form-control" name="email" ng-model="email" required
                    ng-blur="changeFlag(true)" ng-focus="changeFlag(false)">
            <span ng-show="changeFlagBon && userForm.email.$invalid  && !userForm.email.$pristine" class="help-block">邮箱格式错误</span>
        </div>
        <button type="submit" class="btn btn-primary">提交</button>
    </form>
    <!-- 模态弹出窗 -->
    <div class="modal fade" id="showMsgDiv">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title">提示信息</h4>
                </div>
                <div class="modal-body">
                    <p id="showMsg"></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <!--<button type="button" class="btn btn-primary">保存</button>-->
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
    </body>
    </html>
    
    20190826_003131[00-00-00--00-00-29].gif

    相关文章

      网友评论

          本文标题:AngularJs 表单字段合法性校验

          本文链接:https://www.haomeiwen.com/subject/hcslectx.html