Sanity 2.35.0中如何仅在布尔值为true时启用验证?
在Sanity 2.35.0中实现基于布尔值的条件验证
问题背景
需要实现:仅当布尔字段alphaBool设为true时,才要求alphaLoc字段必填。现有代码中,即便alphaBool为false,alphaLoc仍会触发必填错误,且validation回调无法直接获取parent或document对象(但hidden回调可以正常获取)。
相关代码片段:
export default { title: 'Foo', name: 'foo', group: 'general', type: 'object', fields: [ { title: 'Alpha', name: 'alphaBool', type: 'boolean', description: 'Random text', initialValue: false }, { title: 'Alpha Location', name: 'alphaLoc', type: 'string', hidden: ({ parent }) => parent?.alphaBool !== true, validation: Rule => Rule.required() } ] };
解决方法
在Sanity 2.35.0中,需通过Rule.custom()结合context.getDocument()来实现条件验证,具体修改如下:
{ title: 'Alpha Location', name: 'alphaLoc', type: 'string', hidden: ({ parent }) => parent?.alphaBool !== true, validation: (Rule) => Rule.custom((value, context) => { const doc = context.getDocument(); // 根据文档结构层级获取布尔字段值 const isAlphaEnabled = doc?.foo?.alphaBool; // 仅当布尔值为true时校验必填 if (isAlphaEnabled && !value) { return '此字段为必填项'; } return true; }) }
关键说明
Rule.custom()支持自定义验证逻辑,第二个参数context提供getDocument()方法,可获取完整文档对象。- 通过文档结构的层级路径(如
doc?.foo?.alphaBool)定位到目标布尔字段的值。 - 仅在布尔值为
true且当前字段为空时返回错误信息,其余情况验证通过。
内容的提问来源于stack exchange,提问作者GʀᴜᴍᴘʏCᴀᴛ
相关产品推荐
相关产品推荐

