指定字段名称而不是 "value"
specify field name instead of "value"
我必须逐个验证值,而不是为多个值传入整个模式。基于此处的单值验证文档
和这个示例代码
const validator: AnySchema = Joi.string().valid('foo', 'bar').required();
const validationResult: ValidationResult = validator.validate('invalid');
const validationError: ValidationError = validationResult.error;
if (validationError) {
throw validationError;
}
该代码将抛出错误并显示以下错误消息
ValidationError: "value" must be one of [foo, bar]
有什么简单的方法可以用特定名称替换 "value"
吗?因此,当我想验证 environment 时,错误消息可能是
ValidationError: "environment" must be one of [development, production,
test]
或者只有在一次验证多个值时才有可能吗?
您可以使用 any.label(name)
方法并设置自定义标签,该标签也将显示在错误消息中:
Overrides the key name in error messages.
name
- the name of the key.
const schema = {
first_name: Joi.string().label('First Name')
};
你可以简单地做:
const validator: AnySchema = Joi
.string()
.label('Foo/Bar') // Change tha label using label method
.valid('foo', 'bar')
.required();
const validationResult: ValidationResult = validator.validate('invalid');
const validationError: ValidationError = validationResult.error;
if (validationError) {
throw validationError;
}
将输出:
ValidationError: "Foo/Bar" must be one of [foo, bar]
我必须逐个验证值,而不是为多个值传入整个模式。基于此处的单值验证文档
和这个示例代码
const validator: AnySchema = Joi.string().valid('foo', 'bar').required();
const validationResult: ValidationResult = validator.validate('invalid');
const validationError: ValidationError = validationResult.error;
if (validationError) {
throw validationError;
}
该代码将抛出错误并显示以下错误消息
ValidationError: "value" must be one of [foo, bar]
有什么简单的方法可以用特定名称替换 "value"
吗?因此,当我想验证 environment 时,错误消息可能是
ValidationError: "environment" must be one of [development, production, test]
或者只有在一次验证多个值时才有可能吗?
您可以使用 any.label(name)
方法并设置自定义标签,该标签也将显示在错误消息中:
Overrides the key name in error messages.
name
- the name of the key.const schema = { first_name: Joi.string().label('First Name') };
你可以简单地做:
const validator: AnySchema = Joi
.string()
.label('Foo/Bar') // Change tha label using label method
.valid('foo', 'bar')
.required();
const validationResult: ValidationResult = validator.validate('invalid');
const validationError: ValidationError = validationResult.error;
if (validationError) {
throw validationError;
}
将输出:
ValidationError: "Foo/Bar" must be one of [foo, bar]