presence?allowEmpty?
今天我把 created_at 设置成:
{
presence: {
allowEmpty: true
}
datetime: { ... }
}
希望它能允许不传 created_at。但是一旦传了,就必须得通过我设置的 datetime 的检验。
很奇怪的是,我不传 created_at,它直接跟我说:
{
created_at: [
"Created at can't be blank"
]
}
看到这个玩意儿,我满脑子就是,我没设置 allowEmpty: true 吗?翻了翻官网,有这么一句话:
These are the values that are considered empty:
nullundefinedAdditionally you can set the
allowEmptytofalseto disallow the following values:
{}(empty objects)[](empty arrays)""(empty string)" "(whitespace only string)
起初还觉得,empty不是包括了 null 和 undefined 吗,那我 allowEmpty: true 了,不就解放了 null 和 undefined 了吗?
后来才明白过来,它是这个意思:不管你有没有 allowEmpty: true,null 和 undefined 都算empty。想解放 null 和 undefined 就直接跟 validate.js 说:presence: false 就行。如果给它传值的话,会接着往下检验的。
总结
如果想要让 validate 允许不传值,但是一旦传了,就必须得通过检验的话,不用管 allowEmpty,就直接设置:
{
...: {
presence: false,
...
}
}
就行。