在我的node / express应用程序中,我有以下代码。
import Joi from 'joi';
import { Schema, model } from 'mongoose';
const userSchema = new Schema(
{
firstName: {
type: String,
required: true,
minlength: 2,
maxlength: 30,
},
lastName: {
type: String,
required: true,
minlength: 2,
maxlength: 30,
},
email: {
type: String,
required: true,
minlength: 5,
maxlength: 100,
unique: true,
lowercase: true
},
password: {
type: String,
required: true,
minlength: 8,
maxlength: 1024,
},
avatar: {
type: String
},
},
);
export const User = model('User', userSchema);
/** Validate user */
export function validateUser(user) {
const schema = {
firstName: Joi.string().min(2).max(30).required(),
lastName: Joi.string().min(2).max(30).required(),
email: Joi.string().min(5).max(100).required().email(),
password: Joi.string().min(8).max(1024).required(),
confirmPassword: Joi.any().valid(Joi.ref('password')).required().options({ language: { any: { allowOnly: 'Passwords do not match' } } }),
avatar: Joi.string(),
};
return Joi.validate(user, schema, { abortEarly: false });
}
我将abortEarly用作false。验证后的响应是这样的。
[
{
"message": "\"firstName\" is required",
"path": [
"firstName"
],
"type": "any.required",
"context": {
"key": "firstName",
"label": "firstName"
}
},
{
"message": "\"lastName\" is required",
"path": [
"lastName"
],
"type": "any.required",
"context": {
"key": "lastName",
"label": "lastName"
}
},
{
"message": "\"email\" is required",
"path": [
"email"
],
"type": "any.required",
"context": {
"key": "email",
"label": "email"
}
},
{
"message": "\"password\" is required",
"path": [
"password"
],
"type": "any.required",
"context": {
"key": "password",
"label": "password"
}
},
{
"message": "\"confirmPassword\" is required",
"path": [
"confirmPassword"
],
"type": "any.required",
"context": {
"key": "confirmPassword",
"label": "confirmPassword"
}
}
]
我想要的是只包含错误消息的错误数组。但这附带了诸如路径,类型,上下文等其他内容。如何获得这样的更清晰的响应?
{
"firstName": "First name is required",
"lastName": "Last name is required",
"email": "Email must be a valid email"
}