skip to Main Content

I have form like below :

 this.configGroup = new FormGroup({
          accountOne: new FormControl(null),
          accountTwo: new FormControl(null),
          prefix: new FormControl(""),
          suffix: new FormControl(""),
          critical: new FormControl(null),
          medium: new FormControl(null),
          low: new FormControl(null),
          none: new FormControl(null)
       });
   HTML code :
<div class="cred-ref-id-wrap">
        <label for="prefix"
            [invalid]="(!configGroup?.controls?.prefix?.pristine) && (!configGroup?.controls?.prefix?.valid)">
             prefix
            <input
                  [formControlName]="'prefix'" 
                  [placeholder]="'release"
                  [autocomplete]="'off'"
                  (focusout)="getValue('prefix')">
        </label>
   </div>

here I have a situation like user needs to select at least one form control in between suffix or prefix and rest all doesn’t matter but user needs to select compulsory one in between suffix or prefix.
How can be implemented in angular.

2

Answers


  1. You can create a custom Validator and apply it to your form or each control using the setValidators method.
    Here is a quick example :

    const suffixOrPrefixValidator = (formGroup: FormGroup): null => {
        const prefix = formGroup.controls.prefix;
        const suffix = formGroup.controls.suffix;
        if (!prefix.value && !suffix.value) {
            formGroup.controls.prefix.setErrors({ suffixOrPrefix: true });
            formGroup.controls.suffix.setErrors({ suffixOrPrefix: true });
        } else {
            formGroup.controls.prefix.setErrors(null);
            formGroup.controls.suffix.setErrors(null);
        }
        return null;
    };
    
    Login or Signup to reply.
  2. validator is your solution

    function prefixOrSuffixValidator(control: FormGroup): ValidationErrors | null {
      const prefix = control.get('prefix').value;
      const suffix = control.get('suffix').value;
    
      // If both prefix and suffix are empty or null, then this is an error
      if (!prefix && !suffix) {
        return { noPrefixOrSuffix: true };
      }
      return null;
    }
    

    Then added to your form group

    this.configGroup = new FormGroup({
      accountOne: new FormControl(null),
      accountTwo: new FormControl(null),
      prefix: new FormControl(""),
      suffix: new FormControl(""),
      critical: new FormControl(null),
      medium: new FormControl(null),
      low: new FormControl(null),
      none: new FormControl(null)
    }, { validators: prefixOrSuffixValidator });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search