2016-10-05 88 views
0

嗨我正在嘗試使用ng-show驗證密碼,並且即使密碼正確並且頁面刷新時也顯示錯誤消息。密碼驗證在Angular中不起作用

我的代碼是:表單名稱是:registeruser

<!-- Set a password for the account --> 
         <div class="col-md-12" style="margin: 7px;"> 
          <input type="password" id="password" name="password" style="height: 35px;" class="form-control input-lg" placeholder="Password" ng-model="register_password" required autocomplete="off" /> 
          <!-- Button for viewing password --> 
          <input type="checkbox" id="eye" onclick="if(password.type=='text')password.type='password'; else password.type='text';" /> 
         </div> 
         <!-- Error Message for password --> 
         <div class="error-message" ng-show="registeruser.password.$invalid"> 
          Please enter at least 6 characters. 
         </div> 
         <div class="error-message" ng-show="registeruser.password.$pristine"> 
          Please enter your password. 
         </div> 

我查了NG-放映的佔位符名稱,標識和型號名稱,但它不能正常工作。 另外我想要顯示密碼錯誤,如果用戶在密碼字段沒有輸入密碼的情況下退出密碼,並且當密碼字段爲空時不在頁面加載中。

+0

使用ng-messages進行表單驗證。這是實施驗證的簡單且更好的方法,並且會爲您執行大量OOB檢查。下面的鏈接解釋http://www.yearofmoo.com/2014/05/how-to-use-ngmessages-in-angularjs.html –

回答

0

使用$dirty$invalid來顯示錯誤消息。 $dirty由角度設置以確定用戶是否在輸入上放置任何東西。 如果您希望僅在輸入獲得並丟失焦點而沒有任何文本時顯示錯誤消息,則應使用ng-blur/ng-focus來管理輸入的輸入/退出。 默認情況下,只有當用戶通過$ dirty在輸入中插入文本時角度管理,但如果用戶輸入和退出輸入而不輸入文本,則檢測不到更改。

使用$dirty

<input type="password" id="password" name="password" style="height: 35px;" class="form-control input-lg" placeholder="Password" ng-model="register_password" required autocomplete="off" ng-minlength="6" /> 
<!-- Error Message for password --> 
        <div class="error-message" ng-show="registeruser.password.$invalid && registeruser.password.$dirty"> 
         Please enter at least 6 characters. 
        </div> 
0

嘗試這樣的事情。這裏「formSubmitted」是在點擊提交按鈕時設置的作用域變量。你可以在控制器中設置它,如$ scope.formSubmitted = true;在函數內部並使用ng-click提交按鈕來調用它。注意:使用ng-minlength檢查最少6個字符的要求。

<div class="col-md-12" style="margin: 7px;"> 
     <input type="password" id="password" name="password" style="height: 35px;" class="form-control input-lg" placeholder="Password" ng-model="password" ng-minlength="6" required autocomplete="off" /> 
    </div> 

    <!-- Error Message for password --> 
    <div class="error-message" ng-show="(registeruser.password.$error.minlength && !registeruser.password.$pristine) || (registeruser.password.$pristine && formSubmitted)"> 
      Please enter at least 6 characters. 
    </div> 
    <div class="error-message" ng-show="(registeruser.password.$error.required && !registeruser.password.$pristine) || (registeruser.password.$pristine && formSubmitted)"> 
      Please enter your password. 
    </div>