At least one value required for reactive forms

I create a form using ReactiveFormsModule.

I need the user to enter contact details:

  • home phone number
  • cell phone number
  • Email

The form must be valid if a house or mobile phone number is entered, which means that ONE LESS IS ONE . Email is optional.

this.contact = this.fb.group({
    'Festnetz': [],
    'Mobil': [],
    'Email': [],
});

this.contact.valueChanges.subscribe(form => {
    console.log(form, this.contact.status);
});

How to declare that using FormBuilder?

+4
source share
1 answer

You can do something like this:

        this.contact = this.fb.group({
        'Festnetz': [],
        'Mobil': [],
        'Email': [],
    },{validator:(formGroup:FormGroup)=>{
return this.validatePhone(formgroup);

    });

validatePhone(formgroup:FormGroup){
     if(formgroup.controls["Festnetz"].value || formgroup.controls["phone"].value){
            return {validatePhone:true};
            }
            else{
            return null;
            }
    }

OR you can create a separate group for your phone numbers:

    this.contact = this.fb.group({
    'phoneGroup':this.fb.group({
       'Festnetz': [],
            'Mobil': []
    },{validator:(formgroup:FormGroup)=>{
       return this.validatePhone(formGroup);

        }),
            'Email': [],
        });

validatePhone(formgroup:FormGroup){
 if(formgroup.controls["Festnetz"].value || formgroup.controls["phone"].value){
        return {validatePhone:true};
        }
        else{
        return null;
        }
}

. , "Festnetz"

+3

Source: https://habr.com/ru/post/1662948/


All Articles