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()));
}
)
});
✅ 关键说明: