空值
tinyval 将三种值视为空值:undefined、null 和空字符串 ''。
工作方式
| 值 | 必填 Schema(string()、object()…) | optional() | nullable() |
|---|---|---|---|
undefined | required 错误 | 跳过 / 使用默认值 | required 错误 |
'' | required 错误 | 跳过 / 使用默认值 | required 错误 |
null | required 错误 | required 错误 | null |
为什么这样设计
HTML 表单中未填写的字段会以空字符串提交,而不是 undefined。如果把 '' 当作普通字符串,那么必填的“姓名”字段留空也能通过校验,而选填的“网站”字段却会因 URL 格式校验而失败。
Laravel 的做法相同 —— ConvertEmptyStringsToNull 中间件会在校验前把空字符串转换为 null。
常见情况
ts
// 必填:'' 会产生 Required 错误
name: string()
// 选填:'' 和 undefined 会被跳过,字段不会出现在 data 中
website: optional(pipe(string(), pattern(/^https?:\/\//)))
// 选填并带默认值
role: optional(oneOf(['admin', 'user']), 'user')
// 可以为 null(例如来自 JSON)或缺失
middleName: optional(nullable(string()))
// 需要把空字符串作为有效值
comment: optional(string(), '')只包含空格的字符串
' ' 不是空字符串,所以 string() 会接受它。要拒绝这类值,先去除空格再检查长度:
ts
name: pipe(string(), trim(), minLength(1))