首页
/ Valibot 中处理空字符串转为 undefined 的最佳实践

Valibot 中处理空字符串转为 undefined 的最佳实践

2025-05-29 20:17:30作者:贡沫苏Truman

在表单开发过程中,我们经常会遇到用户输入框清空后传递空字符串("")的情况。本文将深入探讨如何在 Valibot 校验库中优雅地将空字符串转换为 undefined 值。

问题背景

当用户在输入框中删除所有内容时,表单控件通常会发出一个空字符串值("")。但在数据模型中,我们可能更希望将其视为 undefined 或 null 值。特别是在使用 Valibot 进行表单校验时,这种转换需求尤为常见。

基础解决方案

最简单的解决方案是使用 transform 方法手动转换:

v.object({
  foo: v.optional(v.pipe(
    v.string(),
    v.transform(val => val.trim() === "" ? undefined : val)
  ))
})

这种方法虽然简单直接,但当我们需要对字符串进行更复杂的校验时(如转换为数字并进行范围校验),就会遇到问题。

进阶场景处理

考虑一个需要将字符串转换为数字并进行范围校验的场景:

const stringToNumberSchema = v.pipe(
  v.string(),
  v.decimal(),
  v.transform(Number),
  v.minValue(0),
  v.maxValue(100)
);

直接使用上述转换方法会导致类型错误,因为 decimal 校验器不接受 undefined 值。

最佳实践方案

Valibot 提供了更优雅的解决方案,通过 union 类型结合 transform 实现:

const Schema = v.optional(
  v.union([
    v.pipe(
      v.literal(''),
      v.transform(() => undefined)
    ),
    v.pipe(
      v.string(),
      v.decimal(),
      v.transform(Number),
      v.minValue(0),
      v.maxValue(100)
    )
  ])
);

这种方法的优势在于:

  1. 明确区分空字符串和其他字符串的处理路径
  2. 保持类型安全,避免运行时错误
  3. 代码结构清晰,易于维护

实际应用建议

在实际项目中,我们可以将这种模式封装为可复用的工具函数:

function optionalString(schema: BaseSchema) {
  return v.optional(
    v.union([
      v.pipe(
        v.literal(''),
        v.transform(() => undefined)
      ),
      schema
    ])
  );
}

// 使用示例
const userSchema = v.object({
  age: optionalString(
    v.pipe(
      v.string(),
      v.decimal(),
      v.transform(Number),
      v.minValue(0),
      v.maxValue(100)
    )
  )
});

总结

Valibot 提供了灵活的方式来处理表单输入中的边界情况。通过合理使用 union 类型和 transform 方法,我们可以优雅地实现空字符串到 undefined 的转换,同时保持严格的类型校验。这种方法不仅解决了当前问题,还为处理其他类似的边界情况提供了可扩展的模式。

登录后查看全文
热门项目推荐
相关项目推荐