要验证表单中是否至少填写了一个字段(复选框或“otherText”字段),请为表单组创建一个自定义验证器。该验证器将检查是否至少选择了一个复选框或是否填写了“otherText”字段。我该怎么做
*我想创建带有两个字段复选框的表单,其他是 otherText,如果两者都是空的,则必须显示错误 *
我已经创建了一个函数来验证至少一个字段是必需的,但它不起作用,请提出任何解决方案或如果其中有任何问题*
*/组件.ts
import { Component } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
function atLeastOneFieldValidator(control: AbstractControl): ValidationErrors | null {
const checkboxValues = Object.values(control.value).filter(value => value === true);
const otherTextValue = control.get('otherText') !.value;
if (checkboxValues.length === 0 && !otherTextValue) {
return { atLeastOneFieldRequired: true };
}
return null;
}
@Component({
selector: 'app-pop-up',
templateUrl: './pop-up.component.html',
styleUrls: ['./pop-up.component.css']
})
export class PopUpComponent {
checkboxForm: FormGroup;
checkboxOptions = ['Custamizable', 'Price', 'Lead `enter code here`Team','Composatable','Biodegradable'];
constructor(private formBuilder: FormBuilder) {
const formControls = this.checkboxOptions.reduce((acc:any, option) => {
acc[option] = [false];
return acc;
}, {});
this.checkboxForm = this.formBuilder.group({
...formControls,
otherText: ['', Validators.required]
}, { validators: atLeastOneFieldValidator });
}
onSubmit() {
const selectedNames = Object.keys(this.checkboxForm.value).filter(key => this.checkboxForm.value[key]);
console.log(selectedNames);
console.log('Other Text:', this.checkboxForm.value.otherText);
}
}
组件.html
<div class="body-container">
<h3>What Matters to You Most ?</h3>
<h4>Select from the following options</h4>
<div >
<form [formGroup]="checkboxForm" (ngSubmit)="onSubmit()">
<div *ngFor="let option of checkboxOptions">
<label>
<input type="checkbox" [formControlName]="option">
{{ option }}
</label><br>
</div>
<div class="others-container">
<label class="others-label">Others</label>
<input class="others-input" type="text" placeholder="Type here..." formControlName="otherText" ><br>
</div>
<div *ngIf="checkboxForm.errors && checkboxForm.errors['atLeastOneFieldValidator']">
<p style="color: red;">At least one field must be filled out.</p>
</div>
<div class="buttonGroup">
<!-- <button class="buttonCancle" (click)="onCancel()">Cancel</button> -->
<button class="buttonSubmit" type="submit">Submit</button>
</div>
</form>
</div>
</div>
function atLeastOneFieldValidator(control: AbstractControl): ValidationErrors | null {
const hasCheckedCheckbox = control.value && Object.values(control.value).some(value => value);
const otherTextValue = control.get('otherText')!.value;
if (!hasCheckedCheckbox && !otherTextValue) {
return { atLeastOneFieldRequired: true };
}
return null;
}
<div *ngIf="checkboxForm.errors && checkboxForm.errors['atLeastOneFieldValidator']">
<p style="color: red;">Hey there! Looks like you forgot to pick something. Choose at least one option or fill in the "Other" field.</p>
</div>
所做的更改: