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>