我有一个函数,它通过obj.pattern. 我想验证的关键是一个格式化的日期,它以以下格式提供给函数DD/MM/YYYY。
我正在使用Joi.date此值进行验证,当一天小于 12 号时,这很好。如果超过,则返回错误。假设是默认的 JOI 格式MM/DD/YYYY显然会导致错误,因为日历年有 12 个月。这反映在控制台日志中 - 如果我将日期值更改为numberField大于 12 的任何值,那么我可以看到错误。如果它保持在下方,则不会引发错误。
我想弄清楚如何格式化此响应,以便 JOI 可以验证正确的模式。我已经将问题简化并简化为我在这里分享的原型:https : //codesandbox.io/embed/naughty-booth-862wb
任何人都可以帮忙吗?
您需要利用包中的.format()方法joi-date来设置自定义日期格式。请参阅内嵌评论。
import "./styles.css";
import JoiBase from "@hapi/joi";
import JoiDate from "@hapi/joi-date";
const Joi = JoiBase.extend(JoiDate); // extend Joi with Joi Date
document.getElementById("app").innerHTML = `
<h1>Hello Vanilla!</h1>
<div>
We use Parcel to bundle this sandbox, you can find more info about Parcel
<a href="https://parceljs.org" target="_blank" rel="noopener noreferrer">here</a>.
</div>
`;
export const dateRequired = (keys, message) => {
return Joi.object().pattern(
Joi.valid(keys),
Joi.date()
.format("DD/MM/YYYY") // set desired date format here
.raw()
.error(() => "message")
);
};
const state = {
numberField: "14/09/1995" // "14/9/1995" will fail without leading "0" on 09
};
const schema = dateRequired(["numberField"]);
const valid = Joi.validate(state, schema); // "valid" is a promise
valid
.then(res => {
console.log("SUCCESS", res);
})
.catch(e => {
console.log("ERROR", e.toString());
});
Run Code Online (Sandbox Code Playgroud)
https://codesandbox.io/embed/prod-grass-f95sz