AngularJS提供了表單驗(yàn)證,但是驗(yàn)證的過(guò)程交互體驗(yàn)很不好,比如重設(shè)密碼,重復(fù)密碼的時(shí)候一鍵入就會(huì)提示密碼不正確,現(xiàn)整理了兩種方法,僅供借鑒。
一,點(diǎn)擊提交驗(yàn)證
<form action="" class="form-horizontal col-md-9" name="reset_pwd" ng-submit="resetPwd()"> <div class="form-group"> <label class="col-sm-2 control-label">密碼</label> <div class="col-sm-8"> <input type="password" name="mycompwd" class="form-control" ng-model="mycompwd" placeholder="請(qǐng)輸入密碼"> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">重復(fù)密碼</label> <div class="col-sm-8"> <input type="password" name="resetmycompwd" class="form-control" ng-model="resetmycompwd" placeholder="再次輸入密碼" required> </div> <span style="color:red" ng-show="mycompwd!=resetmycompwd && reset_pwd.resetmycompwd.$dirty && reset_pwd.submitted ">密碼不一致</span> </div> <div class="form-group"> <button type="submit" class="btn btn-primary" >確認(rèn)</button> <button type="button" class="btn btn-default" ng-click="resetpwd_cancle()">取消</button> </div></form>
當(dāng)用戶(hù)試圖提交表單時(shí),你可以在作用域中捕獲到一個(gè)submitted值,然后對(duì)表單內(nèi)容進(jìn)行驗(yàn)證并顯示錯(cuò)誤信息。
JS代碼
$scope.submitted = false;$scope.resetPwd = function(){ console.log(666); if($scope.reset_pwd.$valid && $scope.mycompwd == $scope.resetmycompwd){ console.log('重置成功,進(jìn)行其他操作'); }else{ $scope.reset_pwd.submitted = true; }}親測(cè)可用。
第二種失去焦點(diǎn)驗(yàn)證
<form action="" class="form-horizontal col-md-9" name="reset_pwd" ng-submit="resetPwd()"> <div class="form-group"> <label class="col-sm-2 control-label">密  碼</label> <div class="col-sm-8"> <input type="password" name="mycompwd" class="form-control" ng-model="mycompwd" placeholder="請(qǐng)輸入密碼"> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">重復(fù)密碼</label> <div class="col-sm-8"> <input ng-focus type="password" name="resetmycompwd" class="form-control" ng-model="resetmycompwd" placeholder="再次輸入密碼" required> </div> <span style="color:red" ng-show="mycompwd!=resetmycompwd && reset_pwd.resetmycompwd.$dirty && !reset_pwd.resetmycompwd.$focused ">密碼不一致</span> </div> <div class="form-group"> <button type="submit" class="btn btn-primary" >確認(rèn)</button> <button type="button" class="btn btn-default" ng-click="resetpwd_cancle()">取消</button> </div></form>
新聞熱點(diǎn)
疑難解答
圖片精選