DEV Community

Cover image for Angular Optional Form Control Validation
John Peters
John Peters

Posted on • Updated on

Angular Optional Form Control Validation

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)

Enter fullscreen mode Exit fullscreen mode

Then hook up changeEvent listener for that form control

// hook up changes listener.
 this.formGroup.controls
   .middleName.valueChanges
     .subscribe((change) => { 
        //inject validators here
      });
Enter fullscreen mode Exit fullscreen mode

The validator pattern to inject on change:

// the form control name is middleName
 middleName.setValidators([
   Validators.pattern(
     //the regex pattern
     middleNamePattern
   )
]);
Enter fullscreen mode Exit fullscreen mode

A good start.

JWP2020 Optional Form Validation

Top comments (0)