How to Validate Phone Number with Angular

How to Validate Phone Number with Angular

In this post, I provide examples of Validate Mobile number With 10 Digits In Angular

In this post, we are going to see how to validate a mobile number with 10 digits in Angular 2/4/5/8 using Pattern Validation. In this case, I have an input text in an Angular form, which validates if a number has 10 digits or not, and accepts only numbers.

Angular provides the PatternValidator directive that adds pattern validator to any control. We use regex as an attribute value.

**app.component.html **

<form #userForm="ngForm" (ngSubmit)="onFormSubmit(userForm)">  
 <table>  
<tr>  
  <td>Mobile Number:</td>  
  <td>  
    <input name="mobileNumber" [ngModel]="user.mobileNumber" [pattern]="mobNumberPattern" #mobNumber="ngModel">  
    <div *ngIf="mobNumber.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'">  
      <div *ngIf="mobNumber.errors.pattern">  
        Mobile number not valid.  
      </div>   
    </div>  
  </td>  
  </tr>    
        
  <tr>      
  <td colspan="2">  
    <button>Submit</button>  
  </td>  
  </tr>      
 </table>   
</form>  

app.component.ts

import { Component } from '@angular/core';  
import { NgForm } from '@angular/forms';  
   
@Component({  
 selector: 'app-root',  
 templateUrl: './app.component.html',  
 styleUrls: ['./app.component.css']  
})  
export class AppComponent {  
 title = 'FormValidation';  
  mobNumberPattern = "^((\\+91-?)|0)?[0-9]{10}$";  
 isValidFormSubmitted = false;  
 user = new User();  
   
   
 onFormSubmit(form: NgForm) {  
   this.isValidFormSubmitted = false;  
   if (form.invalid) {  
      return;  
   }  
   this.isValidFormSubmitted = true;  
   form.resetForm();  
}  
}  
   
export class User {  
 mobileNumber ?: string;  
}  

Output

That's it. You have seen how to validate a mobile number with 10 digits in Angular 2/4/5/8 using Pattern Validator.

Thank you for reading!

Angular 8 Reactive Form Custom Validator Example

Angular 8 Reactive Form Custom Validator Example

how to create custom form validator in angular 8, angular 8 custom validator example, custom validation in angular 8 reactive form, angular 8 custom validator with parameters, angular 8 custom validator directive

Here, i will guide you how to create custom form validator in angular 8 application. you will learn to angular 8 custom validator example step by step. we can simply write custom validation in angular 8 for reactive form.

Custom validation is a most important thing in programming language. most of the cases and most of the project you need to create some custom validation so you can reuse it and also write septate code on file then you can use as like pre define validation.

So if you also need to create custom validator in your angular application then follow bellow step to create basic angular 8 reactive form custom validator.

More: https://www.itsolutionstuff.com/post/how-to-create-custom-validators-in-angular-8example.html

Adding async Validators to your Reactive form in Angular

Adding async Validators to your Reactive form in Angular

Learn how you can add async validators to your reactive form in Angular.

Occasionally, you may want to validate form input against data that is available asynchronous source i.e. a HTTP backend. For instance, checking if a username or email address exists before form submission. In Angular, you achieve this using Async Validators, which we are going to look at in this post.

We are going to build a simple reactive form. It will contain a single form field called username. Then, whenever the user enters their username, we are going to check if it exists and return the response. If the username exists, then the form shall report the following error – The username is already taken., as shown below.

Prerequisite

I am going to skip the process of setting up a new Angular Project. Once you have your Angular project setup, in your app module, you will need to import ReactiveFormsModule from @angular/forms. This is the only module we require to use Reactive Forms inside our angular application.

@NgModule({
  // ...
  imports: [
   BrowserModule,
   ReactiveFormsModule
  ],
  // ...
})

export class AppModule {}

Next, lets add a method for looking up username methods.

Username Lookup Method

First, we are going to add a method to check whether the user’s username exists. In a normal application, this is where you would make a HTTP request to your backend API – either a REST, a GraphQL API etc. But for the purpose of this post, we are going to simulate a HTTP request using RXJS Delay Operator. This will delay our responses by about one second and return an observable just like a HTTP request in Angular.

To achieve this, we are going to create an array of taken usernames - takenUsernames.

takenUsernames = [
  'hello',
  'world',
  'username'
  // ...
];

Then given a username, we are going to determine if it exists within the array using array includes method. After that, whatever the results, we will then delay the response for about a second and return the results as a boolean Observable – Observables<boolean>.

checkIfUsernameExists(username: string): Observable<boolean> {
  return of(this.takenUsernames.includes(username)).pipe(delay(1000));
}

Adding an Async Validator

Next up, we are going to create our async validator. To create this, we just need to implement the <a href="https://angular.io/api/forms/AsyncValidatorFn" target="_blank">AsyncValidatorFn</a> interface. To implement the AsyncValidatorFN interface, you need a method that receives a form control class (AKA <a href="https://angular.io/api/forms/AbstractControl" target="_blank">AbstractControl</a>) as a parameter. The method then needs to return a promise or an observable of ValidationErrors or null. If there are any errors, the method returns ValidationErrors, otherwise it just returns null.

A ValidationErrors is an another interface, which is just a key value map of all errors thrown, as shown below:

type ValidationErrors = {
    [key: string]: any;
};

For instance, our error for this posts demo shall look something like this { usernameExists: true }. The key of the returned error allows you to check for specific errors on your form and display them to the user. This allows you to give a more precise feedback to the user instead of generic feedback.

Please note, when there are no errors, you should always return null. If you don’t return null, your Angular Form will be in an invalid state. This could have some undesired side effects.
In our method to check for errors, we will map the boolean response from checkIfUsernameExists method above to a ValidationErrors or null response. It will return null if false and a ValidationErrors object if true.

usernameValidator(): AsyncValidatorFn {
  return (control: AbstractControl): Observable<ValidationErrors | null> => {
    return this.checkIfUsernameExists(control.value).pipe(
      map(res => {
        // if res is true, username exists, return true
        return res ? { usernameExists: true } : null;
        // NB: Return null if there is no error
      })
    );
  };
}

We will tack the above method inside our username lookup service.

Adding Async Validators to Our Reactive Form

Now that we have a full working service, we need to use the async validator we just created above. This is a simple matter of adding the array of async validators, after synchronous validators, as shown below.

return this.fb.group({
  username: [
    null, [Validators.required],  [this.usernameService.usernameValidator()]
  ]
});

Remember to inject the usernameLookupService into the component you are using it in.

constructor(private fb: FormBuilder, private usernameService: UsernameValidationService) {
  // ...
}

UI Implementation

And finally, inside your template, you can check if the form has errors. You can check if a form field has an validation error inside the template as shown below.

frmAsyncValidator.controls['username'].errors?.usernameExists

This returns true if there is an error, else it is undefined, hence the use of <a href="https://angular.io/guide/template-syntax#safe-navigation-operator" target="_blank">safe navigation operator (?)</a>. And here is the full template for our form:

<form [formGroup]="frmAsyncValidator">
  <div class="field has-text-left">
    <label class="label">Username </label>
    <div [ngClass]="{'is-loading':
frmAsyncValidator.controls['username'].pending }" class="control">
      <input [ngClass]="{'is-danger': hasError('username', 'any')}" formControlName="username" class="input is-focused" type="username" placeholder="Your username">
    </div>
    <div class="has-text-danger" *ngIf="frmAsyncValidator.controls['username'].errors?.usernameExists">
      This username is already taken!
    </div>
  </div>
</form>

A Note on Performance

Currently as we have implemented our async validator, it runs on form value changes. For sync validators, you will likely never notice any performance impact. For async validators however, this can have some undesired side effects. This is because you will most likely be sending HTTP requests to some sort of backend for validation. Running validation on form value changes can end up straining the backend with too many requests.

For this reason, you can change your validators to run onBlur, instead of on form value changes. You can achieve this by adding the updateOn property to { updateOn: 'blur' } for either an individual form control or the entire form:

This is how you can set { updateOn: 'blur' } property for an entire form:

this.fb.group({/** field here */}, { updateOn: 'blur' });

And this is how you do it for an individual form control:

username: [
  null,
  {
    validators: [Validators.required],
    asyncValidators: [this.usernameService.usernameValidator()],
    updateOn: 'blur'
  }
]

Conclusion

That’s it for me in this post. If you have any questions/issue/suggestion, feel free to use the comment section below.

If you liked this post, share it with all of your programming buddies! :)

Angular 8 Forms - How to Validate Forms in Angular using Form Builders

Angular 8 Forms - How to Validate Forms in Angular using Form Builders

In this Angular 8 forms tutorial gives an overview of the form builder in Angular 8 and how to validate forms in Angular 8 using form builders

Forms controls and form groups in Angular

Form controls are basically classes that can hold both the data values and the validation information of any form element, which means to say every form input you have in a reactive form should be bound by a form control. They are the basic units that make up reactive forms.

Form groups are constructs that basically wrap a collection of form controls. Just as the control gives you access to the state of an element, the group gives the same access, but to the state of the wrapped controls. Every single form control in the form group is identified by name when initializing.

Generating form controls

Setting up form controls, especially for very long forms, can quickly become both monotonous and stressful. Angular provides a helper service to solve this problem so that you can always obey the DRY concept of avoiding repetition. This service is called the form builder service.

Before we start…

To be able to follow through this article’s demonstration, you should have:

  • Node version 11.0 installed on your machine
  • Node Package Manager version 6.7 (usually ships with the Node installation)
  • Angular CLI version 8.0
  • The latest version of Angular (version 8)
// run the command in a terminal
ng version

Confirm that you are using version 8, and update to 8 if you are not.

  • Download this tutorial’s starter project here to follow through the demonstrations.
  • Unzip the project and initialize the Node modules in your terminal with this command:
npm install

Other things that would be nice to have are:

  • A working knowledge of the Angular framework at a beginner level
  • Familiarity with form controls in Angular will be a plus but not a requirement
Demo

In this tutorial, you will be taken through a code-along journey building a reactive form with the form builder. If you have followed this post from the start, you will have downloaded and opened the starter project in VS Code. If you open the employee.component.ts, file it should look like this:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms'
@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
  bioSection = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    age: new FormControl(''),
    stackDetails: new FormGroup({
      stack: new FormControl(''),
      experience: new FormControl('')
    }),
    address: new FormGroup({
        country: new FormControl(''),
        city: new FormControl('')
    })
  });
constructor() { }
ngOnInit() {
  }
  callingFunction() {
    console.log(this.bioSection.value);
   }
}

You can see that every single form control — and even the form group that partitions it — is spelled out, so over time, you as the developer keep repeating yourself. The form builder helps to solve this efficiency problem. To use the form builder, you must first register it.

Registering the form builder

To register the form builder in a component, the first thing to do is import it from Angular forms:

import { FormBuilder } from ‘@angular/forms’;

The next step is to inject the form builder service, which is an injectable provider that comes with the reactive forms module. You can then use the form builder after injecting it. Navigate to the employee.component.ts file and copy in the code block below:

import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms'
@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
  bioSection = this.fb.group({
    firstName: [''],
    lastName: [''],
    age: [''],
    stackDetails: this.fb.group({
      stack: [''],
      experience: ['']
    }),
    address: this.fb.group({
        country: [''],
        city: ['']
    })
  });
constructor(private fb: FormBuilder) { }
ngOnInit() {
  }
  callingFunction() {
    console.log(this.bioSection.value);
   }
}

This does exactly the same thing as the previous code block you saw at the start, but you can see there is a lot less code and more structure — and, thus, optimal usage of resources. Form builders not only help to make your reactive forms’ code efficient, but they are also important for form validation.

Form validation

Using reactive forms in Angular, you can validate your forms inside the form builders. Run your application in development with the command:

ng serve

You will discover that the form submits even when you do not input values into the text boxes. This can easily be checked with form validators in reactive forms. The first thing to do, as with all elements of reactive forms, is to import it from Angular forms.

import { Validators } from '@angular/forms';

You can now play around with the validators by specifying the form controls that must be filled in order for the submit button to be active. Copy the code block below into the employee.component.ts file:

The last thing to do is to make sure the submit button’s active settings are set accordingly. Navigate to the employee.component.html file and make sure the submit statement looks like this:

<button type=”submit” [disabled]=”!bioSection.valid”>Submit Application</button>

If you run your application now, you will see that if you do not set an input for first name, you cannot submit the form — isn’t that cool? There are many more cool form validation tips you can get from the official guide here.

Displaying input values and status

The last thing you should know is how to use the value and status properties to display, in real time, the input values of your reactive form and whether it can be submitted or not.

The reactive forms API lets you use the value and status properties on your form group or form controls in the template section. Open your employee.component.html file and copy in the code block below:

<form [formGroup]="bioSection" (ngSubmit)="callingFunction()">
    <h3>Bio Details
</h3>

  <label>
    First Name:
    <input type="text" formControlName="firstName">
  </label> <br>
<label>
    Last Name:
    <input type="text" formControlName="lastName">
  </label> <br>
<label>
    Age:
    <input type="text" formControlName="age">
  </label>
<div formGroupName="stackDetails">
    <h3>Stack Details</h3>

    <label>
      Stack:
      <input type="text" formControlName="stack">
    </label> <br>

    <label>
      Experience:
      <input type="text" formControlName="experience">
    </label>
  </div>
<div formGroupName="address">
    <h3>Address</h3>

    <label>
      Country:
      <input type="text" formControlName="country">
    </label> <br>

    <label>
      City:
      <input type="text" formControlName="city">
    </label>
  </div>
<button type="submit" [disabled]="!bioSection.valid">Submit Application</button>
  <p>
    Real-time data: {{ bioSection.value | json }}
  </p>
  <p>
    Your form status is : {{ bioSection.status }}
  </p>
</form>

This displays both the value and the status for submission for you in the interface as you use the form. The complete code to this tutorial can be found here on GitHub.

Conclusion

This article gives an overview of the form builder and how it is a great efficiency enabler for form controls and form groups. It also shows how important it can be for handling form validation easily with reactive forms. Happy hacking!