MonkeyBonkey
MonkeyBonkey

Reputation: 47851

How to add validators to a formModel in angular reactive forms

I'm following along the reactive form tutorial for angular and was wondering how to make a property as required or any other validator when using class model for the form group definition.

https://angular.io/guide/reactive-forms#the-data-model-and-the-form-model

I noticed that it creates a default empty string as the initial values. Why can't I define the address model without default values - otherwise it throws an error? e.g. I can't say street: string. I suppose having a default value technically fulfills the required validation - but that is not the real-world use case.

Ideally I'd like to define my class models without default values and make the address and certain address fields required. Is this possible using reactive forms and form models?

export class Address {
  street = '';
  city   = '';
  state  = '';
  zip    = '';
}


this.heroForm = this.fb.group({
  name: ['', Validators.required ],
  address: this.fb.group(new Address()), // <-- How to make address and certain address fields required?
  power: '',
  sidekick: ''
});

Upvotes: 0

Views: 388

Answers (1)

Pierre Mallet
Pierre Mallet

Reputation: 7221

You can provider an extra object to add validator or async validator ( see doc here )

this.heroForm = this.fb.group({
  name: ['', Validators.required ],
  address: this.fb.group(new Address(), { validator: Validators.required }), // <-- How to make address required?
  power: '',
  sidekick: ''
});

But in this case the required will not work as your "new Adress()" is an object, thus not null or undefined.

You well have to create a custom validator for you Adress class

    const adressValidator = (fg: FormGroup) => {
         test = fg.value; 

         if (!test.street || !test.city || ... ) {
             return { adress: { valid : false }};
         }
    }

    and 

   this.heroForm = this.fb.group({
      name: ['', Validators.required ],
      address: this.fb.group(new Address(), { validator: adressValidator}), // <-- How to make address required?
      power: '',
      sidekick: ''
    });

Hope it helps

Upvotes: 1

Related Questions