You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Yup的trim方法时为何不显示错误提示?

解决Yup中trim方法不显示错误提示的问题

你的问题出在Yup的.trim()方法本身——它是输入转换方法,不是验证规则。调用.trim()时,Yup会直接自动去掉输入字符串的首尾空格,而不会校验输入是否包含首尾空格,自然不会触发你设置的错误提示。

要实现“禁止首尾空格”的验证,需要用.matches()配合正则来做校验,之后再用.trim()做输入清理(可选,用于合法输入的自动格式化)。修改后的密码字段Schema如下:

password: Yup.string()
            .required('Password is required')
            .min(8, 'Password must be at least 8 characters long')
            .max(18, 'Password cannot be longer than 18 characters')
            .matches(
                /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])/,
                'Password must contain at least one number as well as one uppercase, lowercase, and special character'
            )
            // 新增:验证首尾不能有空格
            .matches(/^\S.*\S$|^\S$/, 'Password cannot include leading and trailing spaces')
            // 保留trim做自动清理(可选)
            .trim()
            .matches(
                /^(?!.*  )/,
                'Password cannot contain two or more consecutive spaces'
            )

说明:

  • 正则/^\S.*\S$|^\S$/的作用:确保字符串首尾都是非空格字符,同时兼容单字符的密码(比如刚好8位的无空格密码)。
  • 把.trim()移到验证规则之后,这样只有通过首尾空格校验的输入才会被自动清理,不会影响错误提示的触发。

内容的提问来源于stack exchange,提问作者Jakob Basshunter Widmann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 14:45:39