2017-08-04 121 views
1

即使tel設置爲可選,但Joi返回以下錯誤。我們如何解決這個問題?Joi:「tel」不允許爲空

謝謝。

Error: Joi Failed: ValidationError: child "tel" fails because ["tel" is not allowed to be empty]


//Define Joi schema 
const schema = { 
    email: Joi.string().required().email({ 
     errorLevel: 64, 
     minDomainAtoms: 2 
    }).min(6), 
    tel: Joi.string().optional().min(10).max(10), 
    password: Joi.string().required().min(8).max(64) 
} 

//Check inputs 
const { error, value } = Joi.validate({ 
    email: args.email, 
    tel: tel, 
    password: args.password 
}, schema) 
+1

[*「需要注意的是空字符串默認不允許的,必須與被啓用'允許( '')'。「*](https://github.com/hapijs/joi/blob/v10.6.0/API.md#string- --inherits-from-any) – jonrsharpe

+0

謝謝。這解決了它完美。 – Kainan

回答

1

...empty strings are not allowed by default and must be enabled with allow('') . However, if you want to specify a default value in case of empty string you have to use a different pattern: Joi.string().empty('').default('default value') . This tells Joi that the empty string should be considered as an empty value (instead of invalid) and which value to use as default.

參考:Joi v10.6.0 Documetations

你的情況:

tel: Joi.string().optional().allow('').min(10).max(10)