joiSite

attempt(value, schema, [message], [options])

스키마에 대해 값의 유효성을 검사하고 유효한 개체를 반환하고 유효성 검사가 실패하면 throw 됩니다.

Joi.attempt('x', Joi.number()); // throws error
const result = Joi.attempt('4', Joi.number()); // result -> 4
const Joi = require('joi');

const schema = Joi.object({
    id: Joi.string()
        .alphanum()
        .min(3)
        .max(30)
        .required(),

    password: Joi.string()
        .alphanum()
				.min(4)
				.max(30)
				.pattern(new RegExp('^[a-zA-Z0-9]{3,30}$'))
				.required()

    repeat_password: Joi.ref('password'),

    access_token: [
        Joi.string(),
        Joi.number()
    ],

    birth_year: Joi.number()
        .integer()
        .min(1900)
        .max(2013),

    email: Joi.string()
        .email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })
})
    .with('username', 'birth_year')
    .xor('password', 'access_token')
    .with('password', 'repeat_password');

schema.validate({ username: 'abc', birth_year: 1994 });
// -> { value: { username: 'abc', birth_year: 1994 } }

schema.validate({});
// -> { value: {}, error: '"username" is required' }

// Also -

try {
    const value = await schema.validateAsync({ username: 'abc', birth_year: 1994 });
}
catch (err) { }
app.get("/api/user/:id", async (req, res) => {
    const { id } = req.params;
   
    // 규칙을 정해준다.
    const schema = Joi.number().min(100).require();

    try {
        // 검사시작
        await schema.validateAsync(id);   
    } catch (e) {
        // 유효성 검사 에러
        return res.status(400).json({ code: 400, message: e.message })
    }

    res.json({ code: 200 })
})

abortEalry option

정의된 key 중 에러가 나면 더 이상 진행하지 않는 것이 기본 동작(abortEarly: true)이다. 한 번에 모든 에러를 확인하고 싶으면 validate 시점에 동작을 제어할 수 있는 validate()의 세 번째 파라미터로 {abortEarly: false}를 설정하면 된다.

const Joi = require('joi');

const schema = Joi.object().keys({
  username: Joi.string().min(3).max(30).required(),
  birthyear: Joi.number().integer().min(1900).max(2018),
});

const user = {
  birthyear: 2020,
};

const options: {
  abortEarly: false,
};

const {error, value} = Joi.validate(user, schema, options);
console.log(error); // Error: child "username" fails because ["username" is required]. child "birthyear" fails because ["birthyear" must be less than or equal to 2018]
console.log(value); // {birthyear: 2020}

assert(value, schema, [message], [options])

Validates a value against a schema and throws if validation fails where:

Joi.assert('x', Joi.number());

key 관계에 조건을 걸 수 있는 .when 예제를 보자.