5

I am new in angular. I have one scenario where I need only one field required from 5 fields in the form, means if the user fills at least one field then form makes valid.

Thanks in advance.

user3492620
  • 83
  • 2
  • 8

4 Answers4

2

Since you need to check for the validity of whole form only if one of the fields is non empty , You can manually set the validity like below :

if(!this.valid){
    this.form.setErrors({ 'invalid': true});
}else{
    this.form.setErrors(null);
}

Where this.valid is your condition based on which you can set the validity

You can check the example : https://angular-exmphk.stackblitz.io

You can also check the answer : FormGroup validation in "exclusive or" which does form validation based on some condition

Hope this helps

CruelEngine
  • 2,701
  • 4
  • 23
  • 44
0

See Custom Validators and Cross-field validation in https://angular.io/guide/form-validation

Exact example from our app, where at least one phone number field must be entered. This is a Validator Function, i.e. implements https://angular.io/api/forms/ValidatorFn

import { AbstractControl } from "@angular/forms";
import { Member } from "../../members/member";

export function phone(control: AbstractControl): {[key: string]: any} {
  if (!control.parent) return;
  const form = control.parent;
  const member: Member = form.value;
  if (member.contactphone || member.mobile || member.contactphonesecond) {
    [
      form.controls['contactphone'],
      form.controls['mobile'],
      form.controls['contactphonesecond']
    ].forEach(control => {
      control.setErrors(null);
    });
  } else return {'noPhone': 'None of contact phones is specified'};
}

Member is our class that defines all the form fields, your code will be different but the example of the custom validator should help.

Nik Dow
  • 584
  • 4
  • 10
-1

Check this example of phone number validator

import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NumberValidator } from '../validators/form-validators';


constructor(
    private fb: FormBuilder){}

FormName: FormGroup = this.fb.group({
    phoneNumber: ['', NumberValidator]    
  });

in form-validator file

import { AbstractControl, ValidatorFn } from '@angular/forms';

export const NumberValidator = (): ValidatorFn => {
  return (control: AbstractControl): { [key: string]: any } | null => {
    const mobileRegex = /^[()-\d\s]*$/g;
    const result = mobileRegex.test(control.value);
    return result ? null : { mobileInvalid: { value: control.value } };
  };
};

let me know if you have any doubts.

Ravi Badoni
  • 87
  • 2
  • 5
  • Thanks for your answer @Ravi. But I have a different scenario. there are many fields in the form. if any filed has data then the form should be valid. – user3492620 Dec 05 '18 at 07:10
  • ok got it. use it like this formfield: [ '', [ValidatorFunction()] ] Create a function name example ValidatorFunction and return the result as valid or invalid. You can submit the form by this way and can also make the form valid if any field have data – Ravi Badoni Dec 05 '18 at 07:15
  • Sorry, I didn't get you. can you please share me the code snippet – user3492620 Dec 05 '18 at 07:23
-1
    <form [formGroup]="formdata">
<div class="form-group">
    <label for="fieldlabel1">fieldLabel1</label>
    <input type="text" id="fieldlabel1" formControlName="fieldName1" class="form-control"><br>
    <label for="fieldlabel2">fieldLabel2</label>
    <input type="text" id="fieldlabel2" formControlName="fieldName2" class="form-control">
</div>
 </form>

<div class="row">
      <div class="col-sm-12">
        <button type="submit" value="submit" (click)="somefunctioncall()" [disabled]="formdata.invalid">
          Submit
        </button>
      </div>
</div>



import { FormGroup, FormControl, Validators } from '@angular/forms';
import { OnInit } from '@angular/core';

export class test {

formdata: FormGroup;

 ngOnInit() {


  this.formdata = new FormGroup({

      fieldName1: new FormControl("", Validators.compose([
        Validators.required
      ])),
      fieldName2: new FormControl("", Validators.compose([
        // remove required validation for one you dont need.
      ]))
    })   
 }
}
Lakshay
  • 536
  • 5
  • 15
  • This is requiring one of the n columns to be set as required... not conditional form validation that prevents either from being required but makes the form invalid if both are empty... – TruncatedCoDr May 04 '21 at 20:22