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();
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()
});
}
}
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,
Set a validator for a control in the FormGroup: this.formSearch.controls['name'].setValidators([Validators.required])
Remove the validator from the control in the FormGroup:
this.formSearch.controls['name'].clearValidators()
Update the FormGroup once you have run either of the above lines. this.formSearch.controls['name'].updateValueAndValidity()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With