我有一个简单的输入,我想在提交时获得错误类型。
formGroup: FormGroup = this.fb.group({
password: [
'',
[Validators.required, Validators.minLength(8), SpecialCharacters],
],
});
例如:
onSubmit(): void {
if (this.formGroup.invalid) {
//I get the type of error:
//number of characters less than 8
//you have not entered any special characters
}
}
您可以使用"hasError((">,以便指定要为每个相应错误返回的消息。
密码字段示例:
onSubmit(): void {
if (this.formGroup.invalid) {
if (this.formGroup.get('password').hasError('minlength')) {
console.log('number of characters less than 8 ');
}
if (this.formGroup.get('password').hasError('SpecialCharacters')) {
console.log('you have not entered any special characters');
}
}
}
另一个选项是访问formGroup控制错误,例如密码字段:
onSubmit(): void {
if (this.formGroup.invalid) {
if (!!this.formGroup.controls.password.errors?.minlength) { // force it to return false if error not found
console.log('number of characters less than 8 ');
}
if (!!this.formGroup.controls.password.errors?.SpecialCharacters)) {
console.log('you have not entered any special characters');
}
}
}
我会为特定的formControl 尝试这样的操作
get getPassword(): AbstractControl {
return this.formGroup.get('password');
}
来自.html
<div *ngIf="getPassword.errors?.minLength">Minimum Length **</div>
<div *ngIf="getPassword.errors?.maxLength">Max Length ***</div>
目前我已经这样解决了:
onSubmit(): void {
if (this.formGroup.valid) {
alert('Password salvata correttamente');
this.formGroup.reset();
} else {
if (this.formGroup.controls.password.errors.minlength) {
alert('ERROR MINLENGTH');
}
if (this.formGroup.controls.password.errors.specialCharacters) {
alert(
'ERROR SPECIALCHARACTERS'
);
}
}
}
没事吧?