Angular 4密码匹配验证规则。
如果您需要对控制字段进行错误设置,则可以这样做。
createForm() {
this.ngForm = this.fb.group({
'first_name': ["", Validators.required ],
'last_name' : ["", Validators.compose([Validators.required, Validators.minLength(3)]) ],
'status' : ['active', Validators.compose([Validators.required])],
'phone':[null],
'gender':['male'],
'address':[''],
'email':['', Validators.compose([
Validators.required,
Validators.email])],
'password':['', Validators.compose([Validators.required])],
'confirm_password':['', Validators.compose([Validators.required])]
}, {validator: this.matchingPassword('password', 'confirm_password')});
}
然后,您需要在constructor
Like 方法中声明此方法。
constructor(
private fb: FormBuilder
) {
this.createForm();
}
而不是在ControlGroup上设置错误,而是对实际字段进行如下设置:
matchingPassword(passwordKey: string, confirmPasswordKey: string) {
return (group: FormGroup): {[key: string]: any} => {
let password = group.controls[passwordKey];
let confirm_password = group.controls[confirmPasswordKey];
if (password.value !== confirm_password.value) {
return {
mismatchedPasswords: true
};
}
}
}
密码组的HTML部分
<form [formGroup]="ngForm" (ngSubmit)="ngSubmit()">
<div class="form-group">
<label class="control-label" for="inputBasicPassword"> Password <span class="text-danger">*</span></label>
<input type="password" class="form-control" formControlName="password" placeholder="Password" name="password" required>
<div class="alert text-danger" *ngIf="!ngForm.controls['password'].valid && ngForm.controls['password'].touched">This Field is Required.</div>
</div>
{{ngForm.value.password | json}}
<div class="form-group">
<label class="control-label" for="inputBasicPassword">Confirm Password <span class="text-danger">*</span></label>
<input type="password" class="form-control" name="confirm_password" formControlName="confirm_password" placeholder="Confirm Password" match-password="password">
<div class='alert text-danger' *ngIf="ngForm.controls.confirm_password.touched && ngForm.hasError('mismatchedPasswords')">
Passwords doesn't match.
</div>
</div>
<button type="submit" [disabled]="!ngForm.valid" class="btn btn-primary ladda-button" data-plugin="ladda" data-style="expand-left" disabled="disabled"><span class="ladda-label">
<i class="fa fa-save"></i> Create an account
<span class="ladda-spinner"></span><div class="ladda-progress" style="width: 0px;"></div>
</span><span class="ladda-spinner"></span></button>
</form>