Hello!
I am trying to validate for either a mobileNumber or landline (at least one has to be entered) but currently validation is passing even though both are empty.
var schema = Joi.object().keys({
fullName: Joi.string().required(),
companyName: Joi.string().required(),
address: Joi.string().required(),
email: Joi.string().required().email(),
mobileNumber: Joi.any(),
landline: Joi.any(),
fax: Joi.optional(),
dx: Joi.optional()
}).or('mobileNumber', 'landline');
Joi.validate(request.payload, schema, {
abortEarly: false
}, function(error, values){
if (error) {
return reply.view("error-page");
} else {
reply.redirect("/");
}
});
I tried using Joi.string() instead of Joi.any() but then that required me to enter a value for both fields even if one of the fields was complete. Could anyone help me out as to what I am doing wrong? Thanks!
Without an actual payload to run it against it's hard for me to do anything with that.
I'm not seeing any problems with this schema:
const schema = Joi.object().keys({
fullName: Joi.string().required(),
companyName: Joi.string().required(),
address: Joi.string().required(),
email: Joi.string().required().email(),
mobileNumber: Joi.any(),
landline: Joi.any(),
fax: Joi.optional(),
dx: Joi.optional()
}).or('mobileNumber', 'landline');
const mobileOnly = {
fullName: 'fullname',
companyName: 'companyname',
address: 'address',
email: '[email protected]',
mobileNumber: '555-555-5555'
};
const landlineOnly = {
fullName: 'fullname',
companyName: 'companyname',
address: 'address',
email: '[email protected]',
landline: '111-111-1111'
};
const neitherLine = {
fullName: 'fullname',
companyName: 'companyname',
address: 'address',
email: '[email protected]',
};
schema.validate(mobileOnly); // error: null
schema.validate(landlineOnly); // error: null
schema.validate(neitherLine); // error: ValidationError: "value" must contain at least one of [mobileNumber, landline
This passes validation when I don't want it to:
request.payload = {
fullName: 'fullName',
companyName: 'companyName',
address: 'address',
email: '[email protected]',
landline: '',
mobileNumber: '',
fax: '',
dx: ''
}
I know it's passing because the values are empty strings but I don't think I can change this since empty input fields are submitted as empty strings. I was really just wondering if there is a solution that will validate for either landline or mobileNumber not being an empty string?
I think using Joi.string().empty('') would do what you expect.
@Marsup beat me to it :( But in my local test, changing the phone number fields to Joi.string().empty('') did the trick. Fails when both are '', passes when one or both is not empty.
Works perfectly! Thanks!
I told you @Marsup is the joi wizard haha
It's a pattern.
Most helpful comment
I think using
Joi.string().empty('')would do what you expect.