Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 5 validation form control update with required

I am using Angular 5. And How do I add required validation to an existing form control??

this.formSearch.get('name').clearValidators();
this.formSearch.get('name').updateValueAndValidity();
like image 684
Charles Morrison Avatar asked Jan 03 '23 22:01

Charles Morrison


1 Answers

Angular comes with a small set of pre-built validators to match the ones we can define via standard HTML5 attributes, namely required, minlegth, maxlength and pattern which we can access from the Validators module.

The first parameter of a FormControl constructor is the initial value of the control, we’ll leave that as empty string. The second parameter contains either a single validator if we only want to apply one, or a list of validators if we want to apply multiple validators to a single control.

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

class ModelFormComponent implements OnInit {
  myform: FormGroup;

  ngOnInit() {
    myform = new FormGroup({
        name: new FormGroup({
            firstName: new FormControl('', Validators.required),
            lastName: new FormControl('', Validators.required),
        }),
        email: new FormControl('', [ 
            Validators.required,
            Validators.pattern("[^ @]*@[^ @]*") 
        ]),
        password: new FormControl('', [
            Validators.minLength(8), 
            Validators.required
        ]),
        language: new FormControl() 
    });
  }
}
  1. We add a single required validator to mark this control as required.
  2. We can also provide an array of validators.
  3. We specify a pattern validator which checks whether the email contains a @ character.
  4. The minlength validator checks to see if the password is a minimum of 8 characters long.
  5. We don’t add any validators to the language select box.

IN YOUR SCENARIO You can use something like this

this.formSearch.controls["name"].setValidators([Validators.required]‌​,[Validators.minLength(1), Validators.maxLength(30)]);

Here you simply pass the FormControl an array of validators. And this will reset any existing validators you added when you created the FormControl.

Additionally,

  1. Set a validator for a control in the FormGroup: this.formSearch.controls['name'].setValidators([Validators.required])

  2. Remove the validator from the control in the FormGroup: this.formSearch.controls['name'].clearValidators()

  3. Update the FormGroup once you have run either of the above lines. this.formSearch.controls['name'].updateValueAndValidity()

like image 150
Lakindu Gunasekara Avatar answered Jan 05 '23 13:01

Lakindu Gunasekara