javascript - Angular 6 Required only one field from many fields Reactive Form - Stack Overflow

I am new in angular. I have one scenario where I need only one field required from 5 fields in the form

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.

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.

Share Improve this question asked Dec 5, 2018 at 6:51 user3492620user3492620 832 silver badges8 bronze badges 5
  • can you share some code that will help us to identify the type of form you are using ? – CruelEngine Commented Dec 5, 2018 at 7:04
  • 1 Any code you already tried? Did you take a look in the documentation? angular.io/guide/reactive-forms#step-2-making-a-field-required – Vanch Commented Dec 5, 2018 at 7:04
  • @CruelEngine .. I am using reactive form with FormGroup. – user3492620 Commented Dec 5, 2018 at 7:08
  • @user3492620 someone has answered it – CruelEngine Commented Dec 5, 2018 at 7:09
  • @CruelEngine. can you please share me the link? – user3492620 Commented Dec 5, 2018 at 7:21
Add a ment  | 

4 Answers 4

Reset to default 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

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.

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.

    <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.pose([
        Validators.required
      ])),
      fieldName2: new FormControl("", Validators.pose([
        // remove required validation for one you dont need.
      ]))
    })   
 }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745064411a4609167.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信