I'm using joi for front-end validation in React. Not using joi-browser since I'm told that was deprecated. Here's a part of the joi schema:
schema = Joi.object({
namePrefix: Joi.string()
.trim()
.alphanum()
.regex(/[a-b]/i)
.min(0)
.max(100)
.messages({
"string.pattern.base": "Name parts should be letters only",
}),
givenName: Joi.string()
.trim()
.alphanum()
.regex(/[a-b]/i)
.min(1)
.max(100)
.messages({
"string.pattern.base": "Name parts should be letters only",
})
.required()});
Here's a prop updating function which also does the validation:
handleUpdateProp = (e, propName) => {
const rule = this.schema.extract(propName);
const subSchema = Joi.object({ [propName]: rule });
const propValue = e.target.value;
const objToValidate = { [propName]: propValue };
const { error } = subSchema.validate(objToValidate);
const validationResult = error ? error : null;
const validationError = validationResult
? validationResult.details[0].message
: null;
const stateErrors = this.state.errors;
stateErrors[propName] = validationError;
this.setState({
[propName]: propValue,
errors: stateErrors,
});
};
namePrefix and givenName correspond to form fields and a div is conditionally rendered under them if there is an error for that field. If I type a character in namePrefix, no error: So far, so good. When I delete the character, joi returns error '"namePrefix" must only contain alpha-numeric characters'
Obviously, no error should be returned because the string is allowed to be empty. Why is this happening? Please help!