Search code examples
node.jsvalidationhapi.js

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.


Solution

  • 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);