Validator minLength FormGroup 响应式表单
Validator minLength FormGroup Reactive form
我正在尝试验证 minLength
但它无法识别它,因为我正在使用一个函数。我也直接在模板中尝试过,但没有得到任何结果。
myComponent.html
<mat-form-field>
<input matInput placeholder="Ingresa tu celular" type="number" formControlName="celular">
<mat-error *ngIf="forma.controls['celular'].invalid">{{ errorCelular() }}</mat-error>
</mat-form-field>
myComponent.ts
celular: [ '', [Validators.required, Validators.minLength(9)] ],
errorCelular() {
return this.forma.controls.celular.hasError('required') ? 'El celular es necesario.' :
this.forma.controls.celular.hasError('minlength')? 'Mínimo 9 caracteres': '';
}
minLength
在 angular 和 type="number"
的早期版本中不起作用。检查 this Github issue 为什么。
如果您不需要输入 type="number"
,请将其更改为 type="text"
,它应该可以工作。如果您需要它是数字类型,那么您应该使用自定义验证器来检查该数字是否大于最小 9 位数字 (100000000)
import { AbstractControl } from '@angular/forms';
function customMinValidator(control: AbstractControl): { [key: string]: boolean } | null {
if (control.value !== undefined && (isNaN(control.value) || control.value >= 100000000 )) {
return { 'customMin': true };
}
return null;
}
然后像-
一样使用它
celular: [ '', [Validators.required, customMinValidator] ]
注意:以上只是在"how"上的使用示例。它不会完全按预期工作,因为对于像 000112313 这样的数字,条件会失败,根据需要,它的 minLength 为 9。但这应该能让您对如何解决它有一个清晰的认识。
我正在尝试验证 minLength
但它无法识别它,因为我正在使用一个函数。我也直接在模板中尝试过,但没有得到任何结果。
myComponent.html
<mat-form-field>
<input matInput placeholder="Ingresa tu celular" type="number" formControlName="celular">
<mat-error *ngIf="forma.controls['celular'].invalid">{{ errorCelular() }}</mat-error>
</mat-form-field>
myComponent.ts
celular: [ '', [Validators.required, Validators.minLength(9)] ],
errorCelular() {
return this.forma.controls.celular.hasError('required') ? 'El celular es necesario.' :
this.forma.controls.celular.hasError('minlength')? 'Mínimo 9 caracteres': '';
}
minLength
在 angular 和 type="number"
的早期版本中不起作用。检查 this Github issue 为什么。
如果您不需要输入 type="number"
,请将其更改为 type="text"
,它应该可以工作。如果您需要它是数字类型,那么您应该使用自定义验证器来检查该数字是否大于最小 9 位数字 (100000000)
import { AbstractControl } from '@angular/forms';
function customMinValidator(control: AbstractControl): { [key: string]: boolean } | null {
if (control.value !== undefined && (isNaN(control.value) || control.value >= 100000000 )) {
return { 'customMin': true };
}
return null;
}
然后像-
一样使用它
celular: [ '', [Validators.required, customMinValidator] ]
注意:以上只是在"how"上的使用示例。它不会完全按预期工作,因为对于像 000112313 这样的数字,条件会失败,根据需要,它的 minLength 为 9。但这应该能让您对如何解决它有一个清晰的认识。