Skip to main content

Angular Form Validation

In this tutorial we will learn how to validate fields in a Angular form using simple-body-validator validation mechanism. We will start with a basic Angular form, and run all the needed validations.

Installation

npm i simple-body-validator

Basic Example

<div>
<form
[formGroup]="profileForm"
(ngSubmit)="onSubmit()"
>
<div>
<label for="name">Name</label>
<input
id="name"
type="text"
formControlName="name"
/>
<p *ngIf="errors.has('name')">{{ errors.first('name') }}</p>
</div>

<div>
<label for="age">Age</label>
<input
id="age"
type="number"
formControlName="age"
/>
<p *ngIf="errors.has('age')">{{ errors.first('age') }}</p>
</div>

<div>
<label for="movie">Favorite Movie</label>
<select
id="movie"
formControlName="movie"
>
<option value="star-wars">Star Wars</option>
<option value="vanilla-sky">Vanilla Sky</option>
<option value="atomic-blonde">Atomic Blonde</option>
</select>
<p *ngIf="errors.has('movie')">{{ errors.first('movie') }}</p>
</div>

<div>
<input
type="submit"
value="submit"
>
</div>
</form>
</div>

Now let's write the Typescript part of the component

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { make, ruleIn, Validator, ErrorBag, InitialRules } from 'simple-body-validator';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
// Create a new validator instance
validator: Validator = make();

// Specify the needed rules
rules: InitialRules = {
age: ['required', 'integer', 'min:18', 'max:64'],
name: ['required', 'string', 'min:3', 'max:255'],
movie: ['required', ruleIn(['star-wars', 'vanilla-sky', 'atomic-blonde'])]
};

profileForm = new FormGroup({
name: new FormControl(''),
age: new FormControl(''),
movie: new FormControl(''),
});

get errors(): ErrorBag {
return this.validator.errors();
}

ngOnInit(): void {
this.validator.setData(this.profileForm.value).setRules(this.rules);
}

onSubmit() {
// Pass the submitted form data to the validator instance and run the validation
this.validator.setData(this.profileForm.value).validate();
}
}

And That's it, when the submit button is clicked, error messages will appear under the related fields. Try to change the values of the fields and click submit again, the error messages will be updated accordingly.

Form Instant Validation Example

Below we will demonstrate an example on how to run the form validation instantly while the user is updating the value of a field. We will consider that you already started with the basic example above, and we will take things from there.

Let's start by adding a new method to our component named onChangeValidate.

onChangeValidate(field: string): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
// only run validation when field is touched or dirty
if (control.touched || control.dirty) {
if (!this.validator.validate(field, control.value)) {
return { [field]: {value: this.errors.first(field) }};
}
}
return null;
}
}
caution

Make sure that you import the following attributes:

import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

On each input change the onChangeValidate method will call the validate method against the new value of the field using its name as reference.

Now the onChangeValidate method needs to be implemented.

    profileForm = new FormGroup({
name: new FormControl('', this.onChangeValidate('name')),
age: new FormControl('', this.onChangeValidate('age')),
movie: new FormControl(''),
});

And that's it, the fields are now being validated dynamically. You can see the whole code and results below.

To read more about handling error messages in simple-body-validator click here.