Angular 反应式表单自定义验证:更改更新第一次无法正常工作
Angular reactive form custom validation : update on change not working on first time
我在我的反应式表单中实现了自定义验证,基本上,当字段长度达到一定限制时它会显示错误。
this.formGroup = new FormBuilder().group({
comment: [null, {
validators: [ValidateCommentLength],
updateOn: 'change'
}]
})
HTML
<textarea
autocomplete="off"
maxlength="3600"
nxInput
(ngModelChange)="valueChange($event)"
type="text"
[formControlName]="'comment'"
></textarea>
<nx-error nxFormfieldError *ngIf="formGroup.get('comment').invalid" appearance="text">
Maximum comment length is exceeded
</nx-error>
</nx-formfield>
但验证不会在第一次输入更改时触发,以后的更改会起作用
更新验证器
import { AbstractControl } from '@angular/forms';
const MAX_LENGTH = 2;
export function ValidateCommentLength(control: AbstractControl) {
if (control.value) {
if (!control.value.replace(/\s/g, '').length) {
return null;
}
const remaining = MAX_LENGTH - control.value.length;
if (!remaining || Math.sign(remaining) === -1) {
return { CommentError: true };
}
}
return null;
}
问题
问题是 nx-error
只有在输入被触摸时才会显示。但是只有当我们模糊形式时才会触及输入
解决方案
验证器使输入无效后,手动触发
export function ValidateCommentLength(control: AbstractControl) {
if (control.value) {
if (!control.value.replace(/\s/g, "").length) {
return null;
}
const remaining = MAX_LENGTH - control.value.length;
if (!remaining || Math.sign(remaining) === -1) {
control.markAsTouched()
return { CommentError: true };
}
}
return null;
}
在上面,我刚刚添加了 control.markAsTouched()
,现在验证工作如您所愿
我在我的反应式表单中实现了自定义验证,基本上,当字段长度达到一定限制时它会显示错误。
this.formGroup = new FormBuilder().group({
comment: [null, {
validators: [ValidateCommentLength],
updateOn: 'change'
}]
})
HTML
<textarea
autocomplete="off"
maxlength="3600"
nxInput
(ngModelChange)="valueChange($event)"
type="text"
[formControlName]="'comment'"
></textarea>
<nx-error nxFormfieldError *ngIf="formGroup.get('comment').invalid" appearance="text">
Maximum comment length is exceeded
</nx-error>
</nx-formfield>
但验证不会在第一次输入更改时触发,以后的更改会起作用
更新验证器
import { AbstractControl } from '@angular/forms';
const MAX_LENGTH = 2;
export function ValidateCommentLength(control: AbstractControl) {
if (control.value) {
if (!control.value.replace(/\s/g, '').length) {
return null;
}
const remaining = MAX_LENGTH - control.value.length;
if (!remaining || Math.sign(remaining) === -1) {
return { CommentError: true };
}
}
return null;
}
问题
问题是 nx-error
只有在输入被触摸时才会显示。但是只有当我们模糊形式时才会触及输入
解决方案
验证器使输入无效后,手动触发
export function ValidateCommentLength(control: AbstractControl) {
if (control.value) {
if (!control.value.replace(/\s/g, "").length) {
return null;
}
const remaining = MAX_LENGTH - control.value.length;
if (!remaining || Math.sign(remaining) === -1) {
control.markAsTouched()
return { CommentError: true };
}
}
return null;
}
在上面,我刚刚添加了 control.markAsTouched()
,现在验证工作如您所愿