如果你在Cyrillic域名验证方面遇到问题,这个解决方案可能会有所帮助。
我们的Yup验证将如下所示
export const Domain = yup.object().noUnknown().shape({
domain: yup.string().domain().required(),
});发布于 2019-04-02 16:28:27
在本教程中,我们将使用扩展标准yup验证的yup.addMethod。
现在我们应该导入模块并定义正则表达式。
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(),
});我们正在生产中使用这个例子,它工作得很好。
祝好运!
https://stackoverflow.com/questions/55470171
复制相似问题