Angular 如何设置角度表单的验证器,以及它是否已经有无效值检测到错误
这里我留下了stackblitz的例子 我正在试验表单,我需要它们根据分配给组合的值更改其验证。e、 这是奖学金的折扣。可以是数量或百分比。如果它是一个百分比,我需要验证它不大于100 我和一个FormGroup一起工作。在angular中,我没有找到一种方法来建立输入的验证并标记错误,而无需编写其他东西进行验证Angular 如何设置角度表单的验证器,以及它是否已经有无效值检测到错误,angular,angular-material,angular-forms,angular-formbuilder,Angular,Angular Material,Angular Forms,Angular Formbuilder,这里我留下了stackblitz的例子 我正在试验表单,我需要它们根据分配给组合的值更改其验证。e、 这是奖学金的折扣。可以是数量或百分比。如果它是一个百分比,我需要验证它不大于100 我和一个FormGroup一起工作。在angular中,我没有找到一种方法来建立输入的验证并标记错误,而无需编写其他东西进行验证 mat-form-field.full-width(appearance="fill") mat-label Sel. type
mat-form-field.full-width(appearance="fill")
mat-label Sel. type desc
mat-select(formControlName="tipo_desc", (selectionChange)="changeTipoDesc($event)")
mat-option(*ngFor="let desc of metadata_prom[0].combo", [value]="desc.valor") {{ desc.desc }}
mat-form-field.full-width(floatLabel="auto", appearance="fill")
mat-label Cant
input(matInput , placeholder="", formControlName="cantidad", autocomplete="off", type="number")
span(matSuffix) {{ symbol }}
mat-error(*ngIf="becaForm.controls.cantidad.invalid")
ng-container(*ngIf="becaForm.controls.cantidad.errors.required; else elseif1") Ingresa una cantidad
ng-template(#elseif1)
ng-container(*ngIf="becaForm.controls.cantidad.errors.max; else elseif2") {{ becaForm.controls.cantidad.errors.max.max }}
ng-template(#elseif2)
ng-container(*ngIf="becaForm.controls.cantidad.errors.pattern") only numbers
请下次提供stackblitz以复制问题。stackblitz不起作用。请提供一个有效的stackblitz链接,是否有任何特定的否决理由?如果我错了,我会很高兴知道的。
_buildForm(data){
let campos = {
descripcion : [{
value : null,
disabled : false
}, [
Validators.required,
Validators.maxLength(50)
]],
tipo_desc : [{
value : null,
disabled : false
}, [
Validators.required
]],
cantidad : [{
value : null,
disabled : false
}, [
Validators.required
]]
};
let form = this._formBuilder.group(campos);
return form;
}
changeTipoDesc(event) {
let [monto, porcentaje]= this.metadata_prom[0].combo
if(monto.valor == event.value) {
this.becaForm.controls.cantidad.setValidators([
Validators.required,
Validators.pattern(/^[0-9]{1,10}$/),
Validators.max(10000)
]);
this.becaForm.controls.cantidad.markAsTouched();
this.becaForm.updateValueAndValidity;
} else if(porcentaje.valor == event.value) {
this.becaForm.controls.cantidad.setValidators([
Validators.required,
Validators.pattern(/^[0-9]{1,10}$/),
Validators.max(100)
]);
this.becaForm.controls.cantidad.markAsTouched();
this.becaForm.updateValueAndValidity;
}
}
if (this.becaForm.controls.get('cantidad').value.indexOf('%') != -1) {
if (Number(this.becaForm.controls.get('cantidad').value) > 100) {
this.becaForm.controls["cantidad"].setErrors({ 'incorrect': true });
this.becaForm.controls["cantidad"].updateValueAndValidity();
} else {
//some logic here
}
}