Joi rejects my optional text field when the client sends '' or null
"value" is not allowed to be emptyShort answer
Joi treats an empty string as invalid and null as a wrong type, and optional() only lets undefined through. Add the values you want to accept with Joi.string().allow('', null). If you use valid() for a fixed list, put '' and null in that list. If an empty form field should mean not sent, use empty('') instead.
Fix it fast
1Find out which cause you have
Run the single rule on its own, outside Express, with the exact value the client sends. The message and the error code tell you which cause below applies.
node -p "const Joi = require('joi'); Joi.string().validate('').error.message"2Match what you see, then jump to its fix
- 1
string.empty: the value is an empty string (''), the field is a stringAn empty string is not allowed on a string by defaultFix - 2
string.base: the input is not a string, and the request body has "field": nullnull is a different type, and optional() does not let it throughFix - 3
any.only: only some values were allowed and the input matched none of themA valid() list for fixed choices does not include the empty valueFix - 4
HTML form or query string fields arrive as '' and the field is optional or has a defaultAn empty form field should mean the field was not sentFix
- 1
What does the error look like?
"value" is not allowed to be emptystring.emptystring.baseany.only
Cause 1 of 4
An empty string is not allowed on a string by default
1Check
The Joi docs say an empty string is not allowed by default on string(). A schema with only Joi.string() or Joi.string().optional() therefore rejects ''. optional() does not help here: it only controls whether the key may be missing.
grep -rn "Joi.string()" src/ | head2Fix
Add the empty string to the values the rule accepts.
const schema = Joi.object({
nickname: Joi.string().allow('')
});3Verify
Validate an empty string against the new schema. The error is gone.
node -p "const Joi = require('joi'); Joi.string().allow('').validate('').error"Confirmed by raw.githubusercontent.com
Cause 2 of 4
null is a different type, and optional() does not let it through
1Check
The docs describe optional() as allowing undefined only and add that it does not allow a null value. JSON clients, mobile apps and ORMs often send null for a field that has no value.
curl -s -X POST http://localhost:3000/profile -H 'Content-Type: application/json' -d '{"nickname": null}'2Fix
Allow null explicitly, next to the empty string if both can arrive. allow() adds values to the ones already accepted, so the ordinary string rules keep working. With express-validation, the rule goes under the body key and Joi is imported from the package itself.
const { validate, Joi } = require('express-validation');
const profileValidation = {
body: Joi.object({
nickname: Joi.string().allow('', null)
})
};
app.post('/profile', validate(profileValidation, {}, {}), handler);3Verify
Send null, an empty string and a real value. All three pass.
node -p "const Joi = require('joi'); const s = Joi.string().allow('', null); [s.validate(null).error, s.validate('').error, s.validate('ok').error]"Confirmed by raw.githubusercontent.com
Cause 3 of 4
A valid() list for fixed choices does not include the empty value
1Check
The docs call allow() additive and say valid() builds an exclusive list. With a field such as a size or a status that uses valid('small', 'large'), '' and null both fail, and the error code is any.only, not string.empty.
grep -rn "\.valid(" src/2Fix
Add the empty value to the list itself.
const schema = Joi.object({
size: Joi.string().valid('small', 'large', '', null)
});3Verify
Validate an empty string and null against the rule.
node -p "const Joi = require('joi'); const s = Joi.string().valid('small', 'large', '', null); [s.validate('').error, s.validate(null).error]"Confirmed by raw.githubusercontent.com
Cause 4 of 4
An empty form field should mean the field was not sent
1Check
Forms send an empty string for an untouched input. If your code treats that as no value, you do not want '' to reach your handler as a string.
grep -rn "req.body" src/ | head2Fix
Use empty('') to tell Joi to treat '' as undefined, and give the field a default if the handler needs one. The validated value then comes out as undefined or the default.
const schema = Joi.object({
nickname: Joi.string().empty('').default('guest')
});3Verify
Validate an object with an empty nickname and read the value back.
node -p "const Joi = require('joi'); Joi.object({ nickname: Joi.string().empty('').default('guest') }).validate({ nickname: '' }).value"Confirmed by raw.githubusercontent.com
How do I stop it coming back?
- Decide per field what 'no value' means (missing, empty string or null) and write that down in the schema once, as allow(), empty() or both.
- With express-validation, import Joi from express-validation so the schema and the validator use the same Joi.
- Add a test for each field that sends '', null and a real value.
- Pass abortEarly: false in joiOptions while developing so one request shows every failing field.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Back end
class-validator rejects null or an empty string on an optional field
A field that may be null is rejected with a validation message
IsOptional only skips validators when the value is null or undefined.
2 causes, each with a fixBack end
Angular app shows 'Cannot GET /' when served by a Node.js server
Cannot GET /dashboard
Cannot GET / is Express saying no route or file matches the request.
3 causes, each with a fixBack end
Axios call from a React app comes back 404
404 (Not Found)
Status code 404 means a server answered, but it has nothing at that path.
3 causes, each with a fixBack end
bcrypt.hash throws 'data and salt arguments required'
Error: data and hash arguments required
The bcrypt package throws this when hash gets null or undefined for the password or for the salt.
4 causes, each with a fixBack end
bcryptjs rejects hash() or compare() with Illegal arguments
Error: Illegal arguments: string, undefined
bcryptjs checks the types of its two arguments and, when either is wrong, throws Illegal arguments followed by the typeof of the first and the second.
3 causes, each with a fixBack end
Express warns 'body-parser deprecated undefined extended'
body-parser deprecated undefined extended
The warning appears because urlencoded() was called without the extended option, which body-parser 1.x has warned about since version 1.4.0.
3 causes, each with a fix