Binge On Code

Jun 21, 2023

15 readers

A Practical Example To Validate Angular Input Fields With Joi

At times, we want to do a quick and custom validation of Angular inputs. Well, how let’s see how we can validate Angular input fields using Joi.

Well, this is an opinionated topic, and it should be, because, why should we want to validate Angular input fields with Joi, yet we have inbuilt Angular form validation?

Well, and yet we are here.

Let’s see how we can use Joi to validate Angular, and from this, you will also learn how to do JavaScript object validation with the same, Joi.

Assumption

In this validate Angular input fields with Joi tutorial, the assumption is that you are here because you already know what Joi is and you want to use your knowledge and apply this to Angular form validation.

If you don’t know what Joi is, please read more from their official website here

Problem

Using joi, please validate a form that accepts the following fields:

  1. firstname.

  2. lastname.

  3. email.

  4. username.

  5. password.

  6. confirm password.

Rules

  1. The first and last names should be required.

  2. If the email is provided, then it should only be a gmail work account email.

  3. username should be less than 10 characters.

  4. password and confirm password should only have numbers in them

Solution

HTML

 

<div class="wrapper">

 <form>

   <input

     (keyup)="validateForm()"

     type="text"

     placeholder="First Name"

     [(ngModel)]="userForm.firstname"

     [ngModelOptions]="{ standalone: true }"

   />

   <input

     (keyup)="validateForm()"

     type="text"

     placeholder="Last Name"

     [(ngModel)]="userForm.lastname"

     [ngModelOptions]="{ standalone: true }"

   />

   <input

     (keyup)="validateForm()"

     type="text"

     placeholder="Email"

     [(ngModel)]="userForm.email"

     [ngModelOptions]="{ standalone: true }"

   />

   <input

     (keyup)="validateForm()"

     type="text"

     placeholder="Username"

     [(ngModel)]="userForm.username"

     [ngModelOptions]="{ standalone: true }"

   />

   <input

     (keyup)="validateForm()"

     type="text"

     placeholder="Password"

     [(ngModel)]="userForm.password"

     [ngModelOptions]="{ standalone: true }"

   />

   <input

     (keyup)="validateForm()"

     type="text"

     placeholder="Confirm password"

     [(ngModel)]="userForm.confirmPassword"

     [ngModelOptions]="{ standalone: true }"

   />

   <button [disabled]="formIsValid">Submit</button>

 </form>

</div>

 

Component

 

import { Component } from '@angular/core';

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


const Joi = require('joi');


interface User {

 firstname?: string;

 lastname?: string;

 email?: string;

 username?: string;

 password?: string;

 confirmPassword?: string;

}


@Component({

 selector: 'app-angular-validation-with-joi',

 templateUrl: './angular-validation-with-joi.component.html',

 styleUrls: ['./angular-validation-with-joi.component.scss'],

 standalone: true,

 imports: [FormsModule],

})

export class AngularValidationWithJoiComponent {

 public userSchema = Joi.object({

   firstname: Joi.string().alphanum().required(),

   lastname: Joi.string().alphanum().required(),

   email: Joi.string()

     .email({

       tlds: { allow: ['gmail'] },

       maxDomainSegments: 2,

     })

     .required(),

   username: Joi.string().max(10),

   password: Joi.string()

     .min(8)

     .pattern(/^[0-9]+/)

     .required(),

   confirmPassword: Joi.ref('password'),

 }).with('password', 'confirmPassword');

 public userForm: User = {};

 public formIsValid: boolean = false;


 ngOnInit(): void {

   this.validateForm();

 }


 public validateForm(): void {

   const { error, value } = this.userSchema.validate(this.userForm);

   this.formIsValid = error ? true : false;

 }

}

 

Discussion

The most important part of the HTML is keyup, where we are actually calling validateForm, which will use Joi to validate Angular form.

The other important thing to note is how we do JavaScript object validation with Joi, by defining the Schema, and then providing each key that is on our JavaScript object, and setting the validation rules.

Conclusion

So with that, you have an alternative method to use when you validate Angular forms.

We can call it wraps here, but remember:

  1. Define the schema.

  2. Define validation rules.

  3. Validate against the schema.

And with that, happy coding and always remember, be good, do good and

God Loves You!

Related Articles

Angular Fix MatFormField Must Contain A MatFormFieldControl

Whenever we are using Angular material, mostly Angular mat-form-field, we get the error that mat-form-field must contain a mat-form-field-control, well, let’s fix that.

Jun 27, 2023

Views 13

Have You Tried Angular Switch Yet

Angular 17 shipped with Angular @switch, and this was a game changer, when it comes to simplicity compared to the former ngSwitch directive. In this guide, we will see how easy it is to use this awesome addition to Angular!

Nov 19, 2024

Views 12

How To Disable Angular HTML Elements Programmatically

At times, we need to disable Angular HTML element like buttons, inputs or even material element, let’s see how we can do this in simple examples.

Jun 19, 2023

Views 46

Angular JavaScript React CSS Django Python React Native Next JS State Management Django Rest Framework Unity