
yup 不支持对同一字段链式调用多个 `.matches()` 实现“或”逻辑校验,但可通过 `.test()` 自定义验证函数,灵活组合多个正则匹配,精准校验 google maps 三类 url 格式。
在使用 Yup 配合 react Hook Form 进行表单验证时,若需对单个字段(如 urlgoogleMaps)支持多种合法格式的 URL(而非所有条件同时满足),直接叠加多个 .matches() 是无效的——因为每个 .matches() 都是独立的“且”校验,输入必须同时满足全部正则才通过,这与业务需求相悖。
正确做法是使用 .test() 方法定义自定义验证逻辑,将多个正则表达式以 逻辑或(||) 方式组合在一个函数中判断。以下是适配你提到的三种 google Maps URL 场景的完整校验方案:
import * as Yup from 'yup'; const requiredMessage = 'Google Maps URL is required'; const areaSchema = Yup.object().shape({ // ... 其他字段 urlGoogleMaps: Yup.string() .required(requiredMessage) .test( 'is-valid-google-maps-url', 'Invalid Google Maps URL. Please enter a valid maps.app.goo.gl, google.com.mx/maps/, or goo.gl/maps/ link.', (value) => { if (!value || typeof value !== 'string') return false; // ✅ 支持三类格式(注意:域名需按实际地区调整,如 .mx、.com 等) const patterns = [ /^https?://maps.app.goo.gl/[a-zA-Z0-9_-]+$/, // e.g., https://maps.app.goo.gl/Abc123 /^https?://www.google.com(.[a-z]{2,3})?/maps/.*/, // e.g., https://www.google.com.mx/maps/place/... 或 https://www.google.com/maps/dir/... /^https?://goo.gl/maps/[a-zA-Z0-9_-]+$/ // e.g., https://goo.gl/maps/XyZ789 ]; return patterns.some(pattern => pattern.test(value.trim())); } ) });
✅ 关键说明:
- 使用 .test() 替代多个 .matches(),实现“任一匹配即通过”的语义;
- 正则中添加 https? 兼容 http(尽管 Maps 实际均为 https,但增强健壮性);
- 对 google.com 后缀支持可选的地区子域(如 .mx, .es, .jp),通过 (.[a-z]{2,3})? 实现;
- 调用 .trim() 防止前后空格导致误判;
- 错误提示信息明确列出三类合法格式,提升用户体验。
⚠️ 注意事项:
- 避免过度宽松的正则(如仅校验 maps 字符串),防止误判 https://example.com/maps-api 等非 Maps URL;
- 若需更高精度(如解析路径参数、校验短链有效性),建议后端二次验证,前端正则仅做基础格式防护;
- 在 React Hook Form 中,确保 resolver 正确集成 Yup Schema(如使用 @hookform/resolvers/yup)。
综上,.test() 是 Yup 中处理“多模式匹配”场景的标准且推荐方式,兼顾灵活性、可读性与可维护性。