Form Validation in Angular

Introduction

The most common issues for web application are a failure to properly validate input coming from the users/clients. UI errors need to be handled in a helping way. Good inputs validation helps application to prompt user proper business exception or error or informative messages to make the app more responsive and user-friendly.

Today in this article, we will cover below aspects,

Good UX (User experience) :

“The best error message is the one that never shows up” — Thomas Fuchs

Sanitize your UI inputs

Apart from user response, improper validation may lead to almost all of the major vulnerabilities in web applications, such as cross-site scripting, interpreter injection, locale/Unicode attacks, and buffer overflow, etc.

“All Input is Evil” _ Michael Howard

This post describes details about input validation in angular forms which will address most of the concerns/aspects discussed above.

Again there are many best practices, guidelines but here in this post, we shall limit to a few. But surely we shall cover those in an upcoming post.

In a nutshell, we will learn below in this post

  • We’ll start off by looking at HTML5 field validation. Next, we’ll look at Angular CSS classes for validation.
  • Next, we’ll look at submitting forms. It’s a common design pattern not to show any form errors until the user attempts to submit the form, so we’ll see how to work with that. 
  • And finally, we’ll look at handling regular HTML5 events with Angular.

We will build on the code that we wrote in the previous blog on the series as below,


HTML5 Field Validation

Before we look at Angular validating fields and validating forms, we need to take a look at HTML5 and see how field validation gets done there.

  • In HTML5, validation is done mainly with attributes on each field.
  • The required attribute marks the input as required. You’ll get an error if there’s nothing entered in that field. 
  • And pattern lets you specify a regular expression for the input control. These are the two main attributes that get used. 
  • We also have some length-based attributes and value-based attributes. 
  • minlength and maxlength let you control the size of the string that gets input, and the min and max work with numbers, which would be an input with a type of number. And it’s the minimum number that’s accepted and the maximum number that would be accepted. 
  • If the entered data follows all of the specified rules, it is considered valid; if not, it is considered invalid.
  • When an element is valid, the following things are true:
    • The element matches the :valid CSS pseudo-class, which lets you apply a specific style to valid elements.
    • If the user tries to send the data, the browser will submit the form, provided there is nothing else stopping it from doing so (e.g., JavaScript).
  • When an element is invalid, the following things are true:
    • The element matches the :invalid CSS pseudo-class, which lets you apply a specific style to invalid elements.
    • If the user tries to send the data, the browser will block the form and display an error message.

Validation Classes in Angular

Angular is constantly looking at our form and adding classes to our input text. This is done for validation purposes. Let’s take a look at the six classes that Angular works with:

ng-untouched & ng-untouched : 

  • A field starts off with the ng-untouched class, and when we visit a field, we may or may not modify it, but at some point we’re going to blur that field, blur means lose focus. 
  • That could mean Tabbing off of the field or hitting the Post button to cause the field to lose focus. 
  • When that happens, the ng-untouched class is removed, and ng-touched is placed on the field. 

ng-pristine and ng-dirty : 

  • A field’s value starts off as pristine, and that means unmodified, and as soon as you modify that field, ng-pristine is removed and ng-dirty is placed on that field. 
  • So a class of ng-dirty just means that the field has been modified. 

ng-valid and ng-invalid : 

  • If we’re using some kind of attribute for a validation, Angular will know about that, and as long as the field is valid, ng-valid will be a class name on that input field. 
  • If the value is invalid, we get ng-invalid instead.

ngModel Properties for Validation


  • We saw how Angular applies classes to the control elements of a form, but it also adds properties to the ngModel object.
  • These classes and properties match up one for one. Let’s see what they are:
    • We have the classes ng-untouched and ng-touched. The associated ngModel properties are simply untouched and touched.
    • Likewise, we have ng-pristine and ng-dirty classes, the properties are pristine and dirty. 
    • For the classes ng-valid and ng-invalid, we simply have valid and invalid as properties.

  • The important thing to remember is that these properties exist on the ngModel object.

Let’s see how we access them.


Accessing ngModel Properties in Code

  • Open user-settings-form.component.html and add the below code in the input field for Name.
  • We create a template reference variable #nameField for the Name field and assign it to string ngModel.
  • Also, we add ‘required’ to make it a mandatory field.
  • We are showing six properties, i-e dirty, pristine, touched, untouched, valid, and invalid. 
  • We have to make sure that nameField references ngModel. The way we do that is by assigning it the string ngModel. 
  • So I’ll save this, run it using ng s –o and let’s look in the browser. 

blank

Styling Forms With Validation Errors

  • Open user-settings-form.component.css and add the below code:

blank

  • We’ll work with the ngSubmit event. 
  • Because it’s an event, it’s in parentheses, and we’ll create a function that we’ll call. We’ll simply call it onSubmit, and we’ll pass it the form.
  • We will call the class ‘field-error’ if the user has not entered a value in the Name field.
  • This validation is done when we submit the form by clicking ‘Send’.
  • In user-settings-form.component.html and add the below code:

blank

  • Let’s create that method, onSubmit, and it takes a form of type NgForm.
  • In user-settings-form.component.ts and add the below code:

blank

  • Add the below import statement at the top for NgForm.

blank

  • I’ll save this and let’s take a look in the browser.

blank

Handling Form Control Events

  • We’re able to handle any HTML5 event in Angular, but the key one we want to look at is the blur event. 
  • When a field loses focus, the blur event is fired, and at that point, we can do custom validation or we could just evaluate the entire form and modify the user interface as needed. 
  • In user-settings-form.component.html and add the below code:

blank

  • In user-settings-form.component.ts and add the below code:

blank

blank

  • Save the changes and run the app in browser.
  • I’ll go to our Name field, and I’ll Tab out of it, and we get the message ‘in onBlur: false, so the field is not valid, which is correct. 

blank

  • But the point I wanted to show here is that now we’re able to add any code we’d like. 
  • You can modify the form based on the value of this field, and you can even show a whole new region of the form based upon the field’s value. So by using Angular events, you have full access to all of the HTML5 events.

Other references :

Source Code Available on GitHub

Please find the code for this app in the below location:

git clone https://github.com/thecodebuzz/angular-8-forms-validation

Summary

In this article, we learned basics about performing forms of validation for a user response in Angular 8 forms. We looked at below,

  • HTML5 Field Validation.
  • Validation Classes in Angular.
  • ngModel Properties for Validation.
  • Styling Forms With Validation Errors.
  • Handling Form Control Events.

Improper validation or weakness may lead to a bad user experience (UX) and could also potentially lead to major vulnerabilities in web applications. So as a good practice it’s important to sanitize all inputs to your application.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



2 thoughts on “Form Validation in Angular

Leave a Reply

Your email address will not be published. Required fields are marked *