Angular Material表單提交及驗證

AngularJS中一些表單驗證屬性:html

  1. 修改過的表單,只要用戶修改過表單,不管輸入是否經過驗證,該值都將返回false
    {formName}.{inputFieldName}.$dirty
  2. 合法的表單,這個屬性用來判斷表單的內容是否合法的,若是合法則該屬性的值爲true
    {formName}.{inputFieldName}.$valid
  3. 不合法的表單,這個屬性用來判斷表單的內容是都不合法,若是不合法則該屬性的值爲true,與valid正好相反
    {formName}.{inputFieldName}.$invalid
  4. 錯誤,$error對象包含了當前表單的全部驗證內容,以及它們是否合法的信息,若是驗證失敗,該屬性值爲true,若是驗證成功,則該值爲false
    {formName}.{inputFieldName}.$error
  5. form表單是否提交,該屬性用來判斷表單是否被用戶提交
    {formName}.$submitted

Angular Material中表單驗證錯誤消息結合使用了ng-messages的用法。如下是一個簡單例子及簡單說明:正則表達式

點擊提交按鈕以後,form標籤中ng-submit將表單的內容進行提交,js中進行是否合法判斷;ui

ng-pattern='/^正則表達式$/'  用來進行自定義表單驗證,通常爲正則表達式。this

ng-messages="{formName}.{inputFieldName}.$error" 用來驗證該表單內容是否錯誤orm

ng-message-exp=['required','minlength','maxlength','pattern']  這裏是所須要驗證的屬性htm

<form name="changePasswordForm" ng-submit="$ctrl.changePassword(changePasswordForm)" ng-cloak novalidate>
<div> <label style="margin-right: 38px; margin-bottom: 0;">密碼</label>   <md-input-container class="md-block no-margin" md-no-float>   <input name="password" type="password" ng-model="$ctrl.data.password" placeholder="請輸入密碼" style="width: 300px" ng-pattern='/^\+?[1-9]*\d$/'
                      minlength="6" maxlength="20"
                      required/>
               <div class="errors" ng-messages="changePasswordForm.password.$error">
                 <div ng-message-exp=['required','minlength','maxlength','pattern']>
                    您輸入的密碼格式不正確
                 </div>
               </div>
           </md-input-container>
    </div>
  <md-button type="submit">提交</md-button>
</form>

<!--js-->
this.changePassword=function(changePasswordForm){
  if(changePasswordForm.$invalid){
  //本次驗證不合法
  return  
  }
}
相關文章
相關標籤/搜索