Angular 带有参数的自定义验证器不适用于文本框和复选框
在我的反应式表单中,我有一个文本框和一个复选框。我希望当复选框被选中时,textbox可以为null或空。若未选中复选框,则应显示所需值的验证消息。因此,我编写了一个带有参数的自定义验证器。但验证器不工作,表单代码如下:Angular 带有参数的自定义验证器不适用于文本框和复选框,angular,angular-reactive-forms,customvalidator,angular-custom-validators,Angular,Angular Reactive Forms,Customvalidator,Angular Custom Validators,在我的反应式表单中,我有一个文本框和一个复选框。我希望当复选框被选中时,textbox可以为null或空。若未选中复选框,则应显示所需值的验证消息。因此,我编写了一个带有参数的自定义验证器。但验证器不工作,表单代码如下: <form [formGroup]="frmExpenseHead"> <div class="form-group row"> <label for="Code" class
<form [formGroup]="frmExpenseHead">
<div class="form-group row">
<label for="Code" class="col-sm-12 col-form-label">Code</label>
<div class="col-sm-10">
<input type="text" class="form-control" [(ngModel)]="txtCode" id="code" name="code" formControlName="code"
[ngClass]="{ 'is-invalid': submitted && f.code.errors }">
<div *ngIf="submitted && f.code.errors" class="invalid-feedback">
<div *ngIf="f.code.errors.conditionRequired">Code is required</div>
</div>
</div>
<div class="col-sm-2 form-check">
<input class="form-check-input" type="checkbox" [(ngModel)]="chkAutoCode" id="autoCode" name="autoCode"
formControlName="autoCode">
<label class="form-check-label" for="autoCode">
Auto Generate
</label>
</div>
</div>
<div class="text-center">
<button class="btn btn-primary mr-1" (click)="onSubmit()">Register</button>
<button class="btn btn-secondary" type="reset" (click)="onReset()">Cancel</button>
</div>
</form>
自定义验证程序是:
export function conditionalRequired(bValue: boolean): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
let controlValue = control.value;
if (bValue === true) {
return null;
}
if (controlValue === "" || controlValue === null || controlValue === undefined) {
return { "conditionRequired": true }
}
return null;
}
}
有人能告诉我哪里出了问题吗?请按照下面的链接查看一个可行的示例
您不必为此创建自定义验证器,请使用可用的工具。这对你来说会容易得多 您可以订阅复选框
FormControl
值的任何更改,然后更改和更新输入FormControl
。下面是一个例子:
@组件({
选择器:“应用程序我的”,
templateUrl:“./my.component.html”,
样式URL:['./my.component.css']
})
导出类MyComponent实现OnInit{
公共前景:FormGroup;
public复选框:FormControl=newformcontrol(false);
公共输入:FromControl=newformcontrol(“”,Validators.required);
公共构造函数(){}
public ngOnInit():void{
this.fg=新表单组({
复选框:this.checkbox,
输入:this.input
});
this.checkbox.valueChanges.subscribe(值=>{
如果(值){
this.input.setValidators(null);
}否则{
this.input.setValidators(Validators.required);
}
this.input.updateValueAndValidity();
});
}
}
谢谢您的回答。是的,有帮助。但我仍然想知道我的代码中有什么错误。由于我是个新手,我正在努力把它学得更好。你能帮我指出我的代码哪里有错吗?我找不到错了。对不起。也许如果你看了这篇文章,你会发现它自己:。您仍然应该使用上面显示的方法。
export function conditionalRequired(bValue: boolean): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
let controlValue = control.value;
if (bValue === true) {
return null;
}
if (controlValue === "" || controlValue === null || controlValue === undefined) {
return { "conditionRequired": true }
}
return null;
}
}