如何设置按条件有效的表单?
How to set form valid by condition?
我有验证表:
public initStep6() {
return this.fb.group({
'name': ['', [Validators.required]]
});
}
另外我在页面上有复选框,如果它被选中,即使字段名称为空,表单也应该有效。
如何在不填写字段的情况下使表单生效?
如果我的理解正确,您希望表单在任一名称有值或复选框(您未包含在表单组中)被选中时有效。您可以在 FormGroup
上使用自定义 ValidatorFn
函数来检查多个字段中的值。这实际上来自表单验证文档中的 Cross Field Validation 示例。它看起来像这样:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, ValidationErrors, ValidatorFn, FormBuilder, Validators } from '@angular/forms';
const myValidator: ValidatorFn = (formGroup: FormGroup): ValidationErrors | null => {
// get controls
const name = formGroup.get('name');
const myCheckbox = formGroup.get('myCheckbox');
// validate however needed, e.g. length/pattern/etc
const isNameValid: boolean = name && name.value && name.value.length > 0;
const isCheckboxValid: boolean = myCheckbox && myCheckbox.value && myCheckbox.value === true;
// return null if valid otherwise return object with custom key/value
return (isNameValid || isCheckboxValid) ? null : { 'formValid': false };
};
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
myFormGroup: FormGroup;
name = 'Angular';
constructor(private fb: FormBuilder) { }
onSubmit() {
console.log('submitted!');
}
ngOnInit() {
// key thing here is passing the ValidatorFn as the 2nd argument to expose the FormGroup in the ValidatorFn rather than a FormControl
this.myFormGroup = new FormGroup({
'name': new FormControl(),
'myCheckbox': new FormControl()
}, { validators: myValidator });
}
}
模板:
<form [formGroup]="myFormGroup" *ngIf="myFormGroup" (ngSubmit)="onSubmit()">
<div>
<label for="name">Name:</label>
<input type="text" name="name" id="name" formControlName="name" />
</div>
<div>
<label for="myCheckbox">My Checkbox:</label>
<input type="checkbox" name="myCheckbox" id="myCheckbox" formControlName="myCheckbox" />
</div>
<div>
<button type="submit" [disabled]="!myFormGroup.valid">Submit!</button>
</div>
<div *ngIf="myFormGroup.errors">
{{myFormGroup.errors | json}}
</div>
</form>
我创建了一个 StackBlitz 来演示功能,包括在表单无效时禁用提交。
希望对您有所帮助!如果这不是您要查找的内容,您确实需要为您的问题添加更多信息。
我有验证表:
public initStep6() {
return this.fb.group({
'name': ['', [Validators.required]]
});
}
另外我在页面上有复选框,如果它被选中,即使字段名称为空,表单也应该有效。
如何在不填写字段的情况下使表单生效?
如果我的理解正确,您希望表单在任一名称有值或复选框(您未包含在表单组中)被选中时有效。您可以在 FormGroup
上使用自定义 ValidatorFn
函数来检查多个字段中的值。这实际上来自表单验证文档中的 Cross Field Validation 示例。它看起来像这样:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, ValidationErrors, ValidatorFn, FormBuilder, Validators } from '@angular/forms';
const myValidator: ValidatorFn = (formGroup: FormGroup): ValidationErrors | null => {
// get controls
const name = formGroup.get('name');
const myCheckbox = formGroup.get('myCheckbox');
// validate however needed, e.g. length/pattern/etc
const isNameValid: boolean = name && name.value && name.value.length > 0;
const isCheckboxValid: boolean = myCheckbox && myCheckbox.value && myCheckbox.value === true;
// return null if valid otherwise return object with custom key/value
return (isNameValid || isCheckboxValid) ? null : { 'formValid': false };
};
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
myFormGroup: FormGroup;
name = 'Angular';
constructor(private fb: FormBuilder) { }
onSubmit() {
console.log('submitted!');
}
ngOnInit() {
// key thing here is passing the ValidatorFn as the 2nd argument to expose the FormGroup in the ValidatorFn rather than a FormControl
this.myFormGroup = new FormGroup({
'name': new FormControl(),
'myCheckbox': new FormControl()
}, { validators: myValidator });
}
}
模板:
<form [formGroup]="myFormGroup" *ngIf="myFormGroup" (ngSubmit)="onSubmit()">
<div>
<label for="name">Name:</label>
<input type="text" name="name" id="name" formControlName="name" />
</div>
<div>
<label for="myCheckbox">My Checkbox:</label>
<input type="checkbox" name="myCheckbox" id="myCheckbox" formControlName="myCheckbox" />
</div>
<div>
<button type="submit" [disabled]="!myFormGroup.valid">Submit!</button>
</div>
<div *ngIf="myFormGroup.errors">
{{myFormGroup.errors | json}}
</div>
</form>
我创建了一个 StackBlitz 来演示功能,包括在表单无效时禁用提交。
希望对您有所帮助!如果这不是您要查找的内容,您确实需要为您的问题添加更多信息。