DEV Community

John Peters
John Peters

Posted on • Updated on

Angular's built-in Validation : Don't use FormControls

New Discovery
Use ngModel instead!

Instant Validation Logic

Alt Text

Not Really Instantaneous

We have to hook up the formGroup and formControl code in the backend to make this work.

Like this:

   private formGroupBind() {   
      if (!this.person) {
         return;
      }
      let namePattern = /^(?=.{1,40}$)[a-zA-Z]+(?:[-'\s][a-zA-Z]+)*$/;
      let ssnPattern = /^(?=.{11}$)\d{1,3}-?\d{1,2}-?\d{1,4}|###-##-####$/;
      this.formGroup = new FormGroup({
         lastName: new FormControl(this.person.lastName, [
            Validators.required,
            Validators.pattern(namePattern),
         ]),
         firstName: new FormControl(this.person.firstName, [
            Validators.required,
            Validators.pattern(namePattern),
         ]),
         middleName: new FormControl(this.person.middleName, []),
         ssn: new FormControl(this.maskedSSN, [
            Validators.required,
            Validators.pattern(ssnPattern),
         ]),
         kind: new FormControl(this.person.kindID, [Validators.required]),
      });

      this.formGroup.enable;
   }
Enter fullscreen mode Exit fullscreen mode

As can be seen there is a distinct pattern. The formGroup is a container for formControls. Each formcontrol is bound the frontend by an object property. We can specify if it's required or not and then use a regex pattern.

If the pattern doesn't match the control will turn pinkish.

We simply do not have to worry about anything else. However we can add niceties for the user experience.

For example anytime a change is made we can hide the save icon based on this code:

this.showSaveIcon == this.formGroup.valid;
Enter fullscreen mode Exit fullscreen mode

Or we can make sure of a valid state prior to saving like this:

  onSave() { 
      if (!this.formGroup.valid) {
         //reject this save it's not valid 
         return;
      }
Enter fullscreen mode Exit fullscreen mode

Where is all this goodness located?

In the forms module for angular. Just import FormsModule and you are all set.

All front-end binding was covered in another post on this same topic.

Alt Text

Summary
Don't write your own validators; use the built-ins. They are faster and have everything you need to maintain proper state for user input.
JWP 2020

Top comments (0)