Signal Forms Validation - Required, Email, Min & Max Length

What is Covered

In this part, validation is added to Signal Forms.

Validations used:

  1. Required
  2. Email
  3. Minimum length
  4. Maximum length


Login Model (Already Created)

loginModel = {
email: '',
password: ''
};


Creating Signal Form with Validation

Required Imports

import {
form,
required,
minLength,
maxLength,
email
} from '@angular/forms/signals';


Adding Validations in Form

loginForm = form(this.loginModel, (field) => {
required(field.email, 'Please enter email address');
minLength(field.email, 5, 'Please enter valid email');
email(field.email, 'Invalid email address');

required(field.password, 'Please enter password');
minLength(field.password, 5, 'Please enter valid password');
maxLength(field.password, 15, 'Please enter valid password');
});

Second parameter of form() is a callback function used to apply validations.


app.html – Input Fields

<input type="text" placeholder="Enter Email" [field]="loginForm.email">
<br><br>

<input type="password" placeholder="Enter Password" [field]="loginForm.password">
<br><br>

<button (click)="login()" [disabled]="loginForm.invalid()">Login</button>
<button (click)="reset()">Reset</button>


Display Email Validation Messages

@if (loginForm.email().touched() && loginForm.email().invalid()) {
<ul>
@for (error of loginForm.email().errors(); track error) {
<li>{{ error.message }}</li>
}
</ul>
}
  1. Errors can be multiple
  2. @for is used to show all error messages
  3. Validation shows only after field is touched


Display Password Validation Messages

@if (loginForm.password().touched() && loginForm.password().invalid()) {
<ul>
@for (error of loginForm.password().errors(); track error) {
<li>{{ error.message }}</li>
}
</ul>
}


Login Function


login() {
console.log(this.loginForm.email.value());
console.log(this.loginForm.password.value());
}


Reset Function


reset() {
this.loginForm.email.set('');
this.loginForm.password.set('');
}


Disable Submit Button Logic

<button [disabled]="loginForm.invalid()">Login</button>
  1. Button is disabled if any field is invalid
  2. Button enables only when all validations pass
  3. After reset, button becomes disabled again