New Discovery
Use ngModel instead!
Assume your web form has an optional field. The field is not required, but when filled in must be valid before submitting the form.
We have discussed tying the Save button visibility to the form being valid. This is a nice way to ensure nothing is submitted before all is good to go. We can leave that code in.
Here's the technique for optional validation on a non-required field.
// Create a formcontrol with no validators at first
middleName: new FormControl(fcPerson.value.middleName)
Then hook up changeEvent listener for that form control
// hook up changes listener.
this.formGroup.controls
.middleName.valueChanges
.subscribe((change) => {
//inject validators here
});
The validator pattern to inject on change:
// the form control name is middleName
middleName.setValidators([
Validators.pattern(
//the regex pattern
middleNamePattern
)
]);
A good start.
JWP2020 Optional Form Validation
Top comments (0)