在这里,我用 stackblitz 留下了这个例子
https://change-validation-form.stackblitz.io
我正在尝试使用表单,我需要它们根据分配给组合的值来更改其验证。例如,这是奖学金的折扣。可以是数量或百分比。如果它是一个百分比,我需要验证它不大于 100。
我正在使用 FormGroup。在 Angular 中,我没有找到一种方法来建立输入验证并标记错误,而无需编写其他东西来验证
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
_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;
}
}