angularjs+ionic注册页面表单验证(手机号、确认密码、60s后重发验证码)
在已建立tabs和路由的注册页面html:
功能:
- 进行了手机号、密码格式验证,两次密码输入是否相同的判断,都正确且复选框勾选后才可点击注册,进入tabs.mypage页面。
- 未进行验证码真正发送、获取后台验证码数据与输入验证码进行对比。
使用:
- 4-- novalidate:禁止执行<form>表单原生校验,避免与自己设置的校验方法起冲突
- 7-- type="number":限定输入数字类型;required:限定不能为空;ng-minlength/ng-maxlength:限定输入字符最小、最大长度
- 11-- type="password":语义化,密码格式;ng-pattern="/[a-zA-Z0-9]/":用正则限定输入数字或字母
- 20-- ng-click="getTestCode()":绑定点击事件;ng-bind="description":控制按钮显示文字;ng-disabled="canClick":控制按钮可用性,避免短时间内多次请求
- 25-- ng-show="":根据条件显示提示文字;registerForm.number:name为registerForm的<form>表单中name为number的<input>输入框;$dirty:<input>输入框已与用户进行交互;$invalid:<input>输入框内容未通过自己设置的校验。
- 33-- ng-disabled="registerForm.$invalid":<form>表单都通过了校验,才可用
注意:不要在<label>标签里添加点击事件!!
1 <ion-view title="注册账号"> 2 <ion-content class="text-center register-content"> 3 <div class="card"> 4 <form name="registerForm" novalidate> 5 <label class="item item-input"> 6 <span class="input-label">手机号</span> 7 <input type="number" placeholder="请输入11位手机号" name="number" required ng-minlength="11" ng-maxlength="11" ng-model="user.number"> 8 </label> 9 <label class="item item-input"> 10 <span class="input-label">输入密码</span> 11 <input type="password" placeholder="6-30位数字或字母" name="password" required ng-pattern="/[a-zA-Z0-9]/" ng-maxlength="30" ng-minlength="6" ng-model="user.password"> 12 </label> 13 <label class="item item-input"> 14 <span class="input-label">确认密码</span> 15 <input type="password" placeholder="再次输入密码" name="password2" required ng-model="password2"> 16 </label> 17 <div class="item item-input"> 18 <span class="input-label col-25">验证码</span> 19 <input type="text" name="testcode" required ng-model="user.testcode"> 20 <button class="button gettestcode col-40" ng-click="getTestCode()" ng-bind="description" ng-disabled="canClick"> 21 </button> 22 </div> 23 </form> 24 </div> 25 <span class="usererr assertive" ng-show="registerForm.number.$dirty && registerForm.number.$invalid">手机号输入有误</span> 26 <span class="usererr assertive" ng-show="registerForm.password.$dirty && registerForm.password.$invalid">密码输入格式有误</span> 27 <span class="usererr assertive" ng-show="registerForm.password2.$dirty && user.password!=password2">两次密码输入不一致</span> 28 <label class="useragree"> 29 <input type="checkbox" name="useragree" ng-checked="true"> 30 <span> 同意<a href="javascript:;">发货么用户协议</a></span> 31 </label> 32 </ion-radio> 33 <button class="button btn-load" ui-sref="tabs.mypage" ng-disabled="registerForm.$invalid">注册</button> 34 <br><br> 35 </ion-content> 36 </ion-view>
在路由绑定的控制器js:
功能:点击触发获取验证码函数,在倒计时59s期间不可再次发送请求。
注意:记得在控制器中注入$interval
1 $scope.canClick=false; 2 $scope.description="获取验证码"; 3 var second=59; 4 var timerHandler; 5 $scope.getTestCode=function(){10 timerHandler=$interval(function(){ 11 if(second<=0){ 12 $interval.cancel(timerHandler); 13 second=59; 14 $scope.description="获取验证码"; 15 $scope.canClick=false; 16 }else{ 17 $scope.description=second+"s后重发"; 18 second--; 19 $scope.canClick=true; 20 } 21 },1000) 22 };