DEV Community

Cover image for Validation made easy in Javascript
HasOne
HasOne

Posted on

Validation made easy in Javascript

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:

# Yarn
$ yarn add joi

# NPM
$ npm install joi

Enter fullscreen mode Exit fullscreen mode

Now let's create our first schema:

const Joi = require("joi");

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

Enter fullscreen mode Exit fullscreen mode

Username: we want username to be validated

  • Joi.string(): it should be string and alphanum()[a-zA-Z0-9]
  • should be minimum 6 and maximum 8 characters
  • and this fields is required

Now let's test it:

const userData = {
  username: 'ericgit'
}
const isValid = schema.validate(userData)
console.log(isValid) // Output: { value: { username: 'ericgit' } }
Enter fullscreen mode Exit fullscreen mode

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

let's do the real world example:

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',
})
Enter fullscreen mode Exit fullscreen mode
  • 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:

const isValid =  schema.validate({
    username: "ericgit",
    birth_day: '01/01/1999',
    password: 'test12',
    repeat_password: 'test12',
    email: 'hi@ericgit.me'
});
Enter fullscreen mode Exit fullscreen mode

you can also do it in try-catch:

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)
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)