验证表单中是否至少填写了一个字段(复选框或其他文本字段),如果两者都为空,则在 Angular 中显示错误?

问题描述 投票:0回答:1

要验证表单中是否至少填写了一个字段(复选框或“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>
html angular forms frontend angular-reactive-forms
1个回答
0
投票
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>

所做的更改:

  • 错误消息: 替换为“必须填写至少一个字段。”带有更随意和友好的信息。
© www.soinside.com 2019 - 2024. All rights reserved.