angular4 實現比較密碼的表單校驗

如今有這樣一個場景:ide

兩個表單控件的值須要比較,而後這個比較若是沒有達到預期效果須要報錯。ui

但無論是響應式表單仍是模板驅動式表單,都只提供基礎的required/min/max等錯誤驗證,因此只能自定義校驗規則this

但這個自定義校驗規則沒法直接添加到表單控件的errors屬性裏spa

若是是響應式表單,能夠使用自定義屬性指令+NG_VALIDATORScode

@Directive({
 selector:'confirmPwd',
 providers:[{
    provide:NG_VALIDATORS,
    useExisting:ConfirmPwdDirective,
    multi:true
 }]
})

export class confirmPwdDirective implements Validator{
 @Input('confirmPwd')  pwd:string   //輸入屬性
 constractor(){}
 validator(control:AbstractControl):{[key:string]:any}{
    return this.pwd?confirmPwdValidator(this.pwd):null;
 }
}

export function confirmPwdValidator(pwd:string):ValidatorFn{
  return (control:AbstractControl):{[key:string]:any}=>{
    if(!control.value) return {'required':true}
    return control.value!==pwd?{'confirmPassword':true}:null
 }

 

<input  [(ngModel)]='inputPwd.new' #new='ngModel'   />
<input  [(ngModel)]='inputPwd.confirm' #confirm='ngModel' [confirmPwd]='new.value'/>

<div class="error-text" *ngIf="confirm.errors?.confirmPassword"> 密碼輸入不一致</div>

 

若是是模板驅動式表單,能夠使用組件+NG_VALUE_ACCESSORorm

@omponent{{
 selector:'nw-input',
 templateUrl:'',
 styleUrls:'',
 providers:[{
    provider:NG_VALUE_ACCESSOR,
    useExisting:forwardRef(()=>NwInputComponent)
 }]
}}

export class NwInputComponent implements ControlValueAccessor{
@Input() hasErrors:any;
}

 

<form [formGroup]="thatForm">
  <nw-input formControlName="pwd" #pwdComp [hasErrors]=formGuard.msgs.pwd.errors></nw-input>
  <nw-input formControlName="confirmPwd" #confirmPwdComp [hasErrors]=formGuard.msgs.confirmPwd.errors></nw-input>
</form>

 

@Component({
  selector:'product-new',
  templateUrl:'',
  styleUrls:''
})

export class productNewComponent implements OnInit{
   thatForm:FormGroup;
formGuard:ProductNewValidation=new ProductNewValidation(); @ViewChild(
'pwdComp') pwdComp:NwInputComponent;

   @ViewChild('confirmPwdComp') confirmPwdComp:NwInputComponent;

   constructor(){}
 
    ngOninit(){
      this.thatForm=this.formBuilder.group({
        pwd:['',Validators,required],
        confirmPwd:['',[Validators.required,MatchValidators.match_pwd('pwd')]]
      })
   }

}

 

export class ProductNewValidation extend FormValidation{
  constructor(){ super()}
  msgs={ 
      pwd:{
         errors:'',
         messages:{
           required:'請輸入密碼'
        }
      },
       confirmPwd:{
         errors:'',
         messages:{
           required:'請再次輸入密碼',
           match:'兩次密碼不一致'
        }
      }
  }
}        

 

export class MatchValidators{
 static match_pwd(targetField:string):ValidatorFn{
      return (control: AbstractControl): { [key: string]: any } => {
          let _form=control.parent;
          if(_form){
                let targetControl:AbstractControl=_form.control[targetField];
                if(targetControl.value && control.value!=taegetControl.value){ 
                     return {match:true}
                }
          }
         return {};       
     }
  }
}
相關文章
相關標籤/搜索