yup 不支持连续调用多个 `.matches()` 实现“或”逻辑,但可通过 `.test()` 自定义验证函数,灵活匹配多种 google maps url 格式(如 `maps.app.goo.gl`、`www.google.com.*\/maps\/`、`goo.gl/maps/`),确保输入符合任一有效模式即可通过校验。
在 Yup 中,.matches() 方法是“与”逻辑——每个调用都会叠加一个独立的正则约束,要求字符串同时满足全部正则,这显然不适用于多选一的 URL 场景(例如既要接受 https://goo.gl/maps/xxx,也要接受 https://maps.app.goo.gl/yyy)。正确做法是使用 .test() 创建自定义验证器,将多个正则以逻辑或(||)组合在一个函数中判断。
以下是适配你列出的三种 Google Maps URL 格式的完整验证方案:
import * as Yup from 'yup';
const googleMapsUrlRegexes = [
/^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:\/\/goo\.gl\/maps\/[A-Za-z0-9_-]+$/ // e.g. https://goo.gl/maps/def456
];
const areaSchema = Yup.object().shape({
// ...其他字段
urlGoogleMaps: Yup.string()
.test(
'is-valid-google-maps-url',
'请输入有效的 Google Maps 链接',
(value) => {
if (!value || typeof value !== 'string') return false;
return googleMapsUrlRegexes.some(regex => regex.test(value.trim()));
}
)
.required('Google Maps 链接为必填项')
});
✅ 关键优势: