1. 程式人生 > >angularjs中form表單提交驗證

angularjs中form表單提交驗證

ng-model pre roots 只需要 dialog onf 如果 date val

angular.module("MyApp",["ngMessages"]);
<form name="formMyName" ng-submit="$ctrl.changePassword(formMyName)" ng-cloak novalidate>
  <--輸入新密碼-->
  <md-input-container md-no-float>
     <input name="newPassword" type="password" ng-model="$ctrl.data.newPassword" placeholder="請輸入密碼
"
      
ng-pattern=/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[~!@#$%^&*(),.])[\da-zA-Z~!@#$%^&*(),.]{6,}$/minlength="6" maxlength="20"required/>   <div class="errors" ng-messages="formMyName.newPassword.$error">
    <--formMyName對應form表單name,newPassword對應input輸入框name,ng-message驗證的是form表單下name為newPassword的input框中ng-pattern、minlength、maxlength、required這些驗證是否通過,
    當驗證不通過時$error為false就會執行ng-message-exp並顯示下面的提示,反之當驗證通過時$error為true。-->   <div ng-message-exp=[
required,minlength,maxlength,pattern]>   您需要輸入6-20位密碼,且必須包括數字、大寫字母、小寫字母、非數字字符。   </div>
    </div
  </md-input-container>

  <--輸入確認密碼-->
  <md-input-container md-no-float>
    <input name="confirmPassword" type="password" ng-modal="$ctrl.data.confirmPassword" placeholder="請輸入確認密碼"/>
    <div ng-if="formMyName.$submitted
&& $ctrl.data.newPassword != $ctrl.data.confirmPassword">
      確認密碼必須和新密碼一致
    </div>
  <--在這個地方確認密碼只需要驗證確認輸入的密碼和新密碼是否一致就可以了,不需要再去驗證最小、最大長度和是否必填那些,因為如果兩次密碼一致的話上面那些驗證是一定通過的,如果兩次密碼不一致上面那些驗證也就沒有意義的,
    然後我們可以看到,這裏用的是ng-if進行的判斷,但是ng-if不屬於表單驗證,所以後面我們需要用js再進行驗證。我們看ng-if裏面的條件,formMyName對應form表單name,$submitted表示的是當點擊提交按鈕時進行驗證。-->
  </md-input-container>

  <md-button type="submit">
    提交
  </md-button>
</form>
angular.module().controller(, [
    $rootScope, $mdDialog,
    function ($rootScope, $mdDialog) {
        var data = this.data = {
            Password: null,
            ConfirmPassword: null
        };
    //修改密碼
        this.changePassword = function (changePasswordForm) {
    //驗證輸入內容有沒有通過表單驗證
    //驗證確認密碼與新密碼是否一致
if (changePasswordForm.$invalid || data.Password != data.ConfirmPassword) { return } $mdDialog.hide(data.Password); }; } ]);

angularjs中form表單提交驗證