$scope.regex = /^1[34578]d{9}$/;
1.对手机号进行了验证
2.现在添加的时候会进行验证
3.但是编辑的时候,如果之前的手机号填写有错,不会提示,这样保存的时候会出错。
保存时是这样判断的
PHPz2017-05-15 17:14:49
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();
};
某草草2017-05-15 17:14:49
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.
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.
PHP中文网2017-05-15 17:14:49
Try writing ng-pattern="/^1/" (the regex you wrote) directly on the interface. Do not use variable definitions