Validation made easy in Javascript
Tags: webdev, showdev, frontend, node
Published: 2022-05-30 12:49:52

---
title: Validation made easy in Javascript
published: true
description: A robust way to validate user data in fastest way.
tags: #webdev #showdev #frontend #node
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s1qkp51nsu8g74xs1yy9.png
---


In past we were handling validation by creating our own logic and some extra function, if the user is null or empty, throw an error and same for email, password and son on. in today's article we'll be learning about a cool package which do everything for us, we just need to create a schema, it saves a lot of time and boost your development process. isn't it cool? yeah 

let's do it, first we'll be installing [`Joi`](https://www.npmjs.com/package/joi):

```sh
# Yarn
$ yarn add joi

# NPM
$ npm install joi

```

Now let's create our first schema:
```js
const Joi = require("joi");

const schema = Joi.object({
   username: Joi.string().alphanum().min(3).max(8).required()
})

```
**Username**: we want username to be validated
- Joi.string(): it should be string and [alphanum()](https://en.wikipedia.org/wiki/Alphanumericals)[a-zA-Z0-9]
- should be minimum 6 and maximum 8 characters 
- and this fields is required

Now let's test it:

```js
const userData = {
  username: 'ericgit'
}
const isValid = schema.validate(userData)
console.log(isValid) // Output: { value: { username: 'ericgit' } }
```

if there is any error, it will throw an error with the corresponding message.


let's do the real world example:
```js
const Joi = require("joi");

const schema = Joi.object({
  username: Joi.string().alphanum().min(3).max(8).required(),
  email: Joi.string().email({ minDomainSegments: 2, tlds: false }),
  phone: Joi.string().length(10).pattern(new RegExp('/^[0-9]+$/')),
  birth_day: Joi.date(),
  password: Joi.string().pattern(new RegExp("^[a-zA-Z0-9]{3,30}$")),
  repeat_password: Joi.ref('password'),
  access_token: [Joi.string(), Joi.number()]
}).with('username', 'birth_day')
    .xor('password', 'access_token')
    .with('password', 'repeat_password');



// Validating data
const isValid = schema.validate({
    username: "ericgit",
    birth_day: '01/01/1999',
})
```

- `with('username', 'birth_day')`: you have to pass `birth_day` property along with user, so username field make it requried.
- `xor('password', 'access_token')`: we either pass `password` or `access_token`. so one of them, not two these two properties at the same time.

#### Example two:
```js
const isValid =  schema.validate({
    username: "ericgit",
    birth_day: '01/01/1999',
    password: 'test12',
    repeat_password: 'test12',
    email: 'hi@ericgit.me'
});
```

you can also do it in `try-catch`:
```js
try {
    const isValid = await schema.validateAsync({
        username: "ericgit",
        birth_day: '01/01/1999',
        password: 'test12',
        repeat_password: 'test12',
        email: 'hi@ericgit.me'
    });
} catch (error) {
    console.log(error)
}
```


## Final word

I was recently implementing the realtime changes feature in flask + React app, I came across this library, thought to share it with the community and I personally loved it as it's time saving and more advanced things we can control in it. we can use it React, Node and any framework.

I hope you will find it helpful and thank you for reading it
Stay blessed && Stay safe, Happy coding.