angular.js - ng-pattern validation issue
某草草
某草草 2017-05-15 17:12:49
0
3
747

$scope.regex = /^1[34578]d{9}$/;

1. The mobile phone number has been verified
2. It will be verified when adding it now
3. However, when editing, if the previous mobile phone number was filled in incorrectly, there will be no prompt. When saving, Something will go wrong.
This is how it is judged when saving

某草草
某草草

reply all(3)
PHPzhong

If you want the input输入的时候验证 + form提交的时候验证
第一步:给要验证的 input 添加 onkeyup 事件,在键盘松开的时候触发验证
第二步:给 form 添加 onsubmit event, verify it when the form is submitted

Here is an example:
HTML:

<form action='url' id='login_form'>
    手机号:<input type='number' name='phone' />
    提交:<input type='submit' value='提交' />
</form>

Javascript

var form     = document.forms['login_form']
var phoneNum = form.elements['phone'];
var phoneReg = /^1[34578]\d{9}$/;

// 检测手机号码
var checkUserPhoneNum = function(){
    var phoneVal = phoneNum.value;
    
    // 表单验证
    if (!phoneReg.test(phoneVal)) {
        return false;
    }
    
    return true;
};

// 手机号码输入的时候验证
phoneNum.onkeyup = function(){
    if (!checkUserPhoneNum()){
        // 手机号码不正确的时候要做的事情....
        return ;
    }
    
    // 手机号码正确的时候要做的事情....
};

// 表单提交
form.onsubmit = function(event){
    // 首先阻止表单提交
    event.preventDefault();
    
    // 手机号码验证
    if (!checkUserPhoneNum()){
        console.log('请输入正确的11位手机号码');
        return ;
    }
       
    // 通过验证,则提交表单
    this.submit();
};
某草草

can be changed to:

if ($scope.userform.$dirty && $scope.userform.$invalid) {}

In fact, it is reasonable to not allow submission when there are no changes $scope.userform.$dirty.

========UPDATE========

There is a big problem with the way you write the form.

angular comes with a verification model of html5 attributes

The angular form itself contains verification of most HTML5 form elements, such as: required. To enable it, add ng-submit="adduserinfo()",既然有验证模型,那就去掉浏览器自身的验证,再加上 novalidate to from.

Since the form adds a submit action, the OK button does not need anything related to events.

<form name="userform" novalidate ng-submit="adduserinfo()" id="user_form">
    <button class="studentadd" type="submit">确定</button>
</form>

In fact, Angular’s ​​own verification model is still very rich, especially with regular expressions, there are many things that can be done.

Ty80

Try writing ng-pattern="/^1/" (the regex you wrote) directly on the interface. Do not use variable definitions

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template