loksan
loksan

Reputation: 177

Password validation using Joi

I am trying to validate the password entered by the user. The password should have a minimum length of 4 and should contain both characters and numbers.I am using Joi npm module for validation.

app.js code:

const schema = Joi.object({
  email: Joi.string().email().required(),
  username: Joi.string().alphanum().min(3).required(),
  password: Joi.string().min(4).required(),
});
app.post('/register',async (req,res)=>{
  try{
       const value = await schema.validateAsync({
         email: req.body.email,
         username: req.body.username,
         password: req.body.password,
        });

  }catch(e){ 
  console.log(e)}
})

How do I check if both characters and numbers are present in the user's password? I am not using Regex expression here. Can somebody help?

Upvotes: 4

Views: 9499

Answers (3)

TeaDrinker
TeaDrinker

Reputation: 473

Joi
.string()
.regex(/[0-9a-zA-Z]*\d[0-9a-zA-Z]*/) // at least one digit in any position
.regex(/[0-9a-zA-Z]*\[a-zA-Z][0-9a-zA-Z]*/) // at least one letter in any position
.min(4)

Tips:

  • \w is equivalent to [0-9a-zA-Z_] in javascript. So if you want to include underscore, choose this.
  • If you want to include all printable symbols, choose this: [ -~]. (Note the beginning space)

Upvotes: 0

Jendorski Labs
Jendorski Labs

Reputation: 527

Use confirmPassword: Joi.ref('password') instead.

Upvotes: 0

narotham sai
narotham sai

Reputation: 64

You can use alphanum()

password: Joi.string().min(4).alphanum().required()

Check out https://joi.dev/api/?v=17.2.1#stringalphanum

Upvotes: -1

Related Questions