如果您在使用Cyrillic域名验证时遇到麻烦,此解决方案可能会有所帮助。
我们的Yup验证看起来像这样
export const Domain = yup.object().noUnknown().shape({
domain: yup.string().domain().required(),
});
答案 0 :(得分:0)
在本教程中,我们将使用yup.addMethod扩展标准的yup验证。
现在我们应该导入模块并定义正则表达式。
import * as yup from 'yup';
const patterns = [
domain: /^(?!:\/\/)([a-zA-Z0-9-_]+\.)*[a-zA-Z0-9][a-zA-Z0-9-_]+\.[a-zA-Z]{2,11}?$/,
punycode: /^([A-Za-z0-9](?:(?:[-A-Za-z0-9]){0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:(?:[-A-Za-z0-9]){0,61}[A-Za-z0-9])?)*)(\.?)$/,
cyrillicDomain: /^((http|https):\/\/)?[a-zа-я0-9]+([\-\.]{1}[a-zа-я0-9]+)*\.[a-zа-я]{2,5}(:[0-9]{1,5})?(\/.*)?$/i,
];
扩展标准架构
yup.addMethod(yup.string, 'domain', function pattern(name, message = VALIDATION_ERRORS.domain) {
const domainRules = [patterns.domain, patterns.punycode, patterns.cyrillicDomain];
return this.test({
message,
test: value => (value === null || value === '' || value === undefined) || domainRules.some(regex => regex.test(value)),
});
});
下一步是在yup模式中添加验证
export const Domain = yup.object().noUnknown().shape({
domain: yup.string().domain().required(),
});
我们正在生产中使用此示例,并且效果很好。
祝你好运!