DEV Community

Cover image for Angular Optional Form Control Validation
JWP
JWP

Posted on • Edited on

5

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)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay