Jitendra
Jitendra

Reputation: 3185

how to validate request parameters in hapi and joi with regex

I am new to hapi and i started with simple form submitting and need to validate my form data. For that i got functionality by using the module "joi". But with joi model how can i validate my data by regex validation on strings like username and password with a pre-specified format.

Upvotes: 3

Views: 2299

Answers (2)

Krishan Kant Sharma
Krishan Kant Sharma

Reputation: 361

Try this :

var Joi = require('joi')

server.route({  
  method: 'POST',
  path: '/',
  config: {
    handler: function (request, reply) {
      // do any processing

      reply('Your response data')
    },
    validate: {
      payload: {
        email: Joi.string().email().required(),
        password: Joi.string().min(6).max(200).required()
      }
    }
  }
})

Upvotes: 0

Manjeet Singh
Manjeet Singh

Reputation: 2398

You can use like this

joi link on github
joi

var schema = Joi.object().keys({  
        username: Joi.string().regex(/[a-zA-Z0-9]{3,30}/).min(3).max(30).required(),
        password: Joi.string().regex(/[a-zA-Z0-9]{3,30}/),
        confirmation: Joi.ref('password')
      })
      .with('password', 'confirmation');

    // will fail because `foo` isn't in the schema at all
    Joi.validate({foo: 1}, schema, console.log);

    // will fail because `confirmation` is missing
    Joi.validate({username: 'alex', password: 'qwerty'}, schema, console.log);

    // will pass
    Joi.validate({  
      username: 'alex', password: 'qwerty', confirmation: 'qwerty'
    }, schema, console.log);

Upvotes: 4

Related Questions