最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JOI validation string fails on , and - Stack Overflow

programmeradmin5浏览0评论

I use joi for validation and am trying to validate a ments textarea content in the following way:

const schema = Joi.object().keys({
    firstName: Joi.string().alphanum().min(3).max(30).required(),
    lastName: Joi.string().alphanum().min(3).max(30).required(),
    pany: Joi.string().alphanum().min(3).max(30).required(),
    ments: Joi.string().alphanum().min(30).max(1500).required(),
    email: Joi.string().email().required()
});

However, if anyone enters a ma or fullstop, the validation fails. How can I add those exceptions to the validation?

I use joi for validation and am trying to validate a ments textarea content in the following way:

const schema = Joi.object().keys({
    firstName: Joi.string().alphanum().min(3).max(30).required(),
    lastName: Joi.string().alphanum().min(3).max(30).required(),
    pany: Joi.string().alphanum().min(3).max(30).required(),
    ments: Joi.string().alphanum().min(30).max(1500).required(),
    email: Joi.string().email().required()
});

However, if anyone enters a ma or fullstop, the validation fails. How can I add those exceptions to the validation?

Share Improve this question edited Dec 18, 2017 at 20:41 Patrick Hund 20.2k12 gold badges70 silver badges95 bronze badges asked Dec 18, 2017 at 17:18 ArihantArihant 4,04718 gold badges59 silver badges91 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

Since you probably would want to allow people to anything in the ments field, I would simply leave out the alphanum for the ments validation, like this:

const schema = Joi.object().keys({
    firstName: Joi.string().alphanum().min(3).max(30).required(),
    lastName: Joi.string().alphanum().min(3).max(30).required(),
    pany: Joi.string().alphanum().min(3).max(30).required(),

    // note: no alphanum here
    ments: Joi.string().min(30).max(1500).required(),

    email: Joi.string().email().required()
}); 

If you really, really must have ments that contain only letters, numbers, mas and periods, you could resort to using the regex rule:

const schema = Joi.object().keys({
    // ...
    ments: Joi.string().regex(/^[,. a-z0-9]+$/).required(),
    // ...
}); 

You can use a regex that includes alphanumeric characters plus ma. I have no idea what you mean by fullstop btw.

Joi.string().regex(/^[a-zA-Z0-9, ]*$/, 'Alphanumerics, space and ma characters').min(3).max(30).required()

Note this will literally only match the characters in ranges a-z, A-Z, 0-9 and the space and ma characters. Anything else (like the period character, brackets, parenthesis?) you would need to add.

Source is the Joi API docs.

You can simply use Regex syntax for the same ments: Joi.string().regex(/^[a-zA-Z0-9,. ]*$/).min(3).max(30).required()

发布评论

评论列表(0)

  1. 暂无评论