Javascript punycode和西里尔文的Yup域名验证

Javascript punycode和西里尔文的Yup域名验证,javascript,reactjs,react-native,formik,yup,Javascript,Reactjs,React Native,Formik,Yup,如果您在Cyrillic域名验证中遇到问题,此解决方案可能会有所帮助 是的,我们的验证是这样的 export const Domain = yup.object().noUnknown().shape({ domain: yup.string().domain().required(), }); 在本教程中,我们将使用yup.addMethod扩展标准yup验证 现在我们应该导入模块并定义regex import * as yup from 'yup'; const patterns =

如果您在Cyrillic域名验证中遇到问题,此解决方案可能会有所帮助

是的,我们的验证是这样的

export const Domain = yup.object().noUnknown().shape({
  domain: yup.string().domain().required(),
});

在本教程中,我们将使用yup.addMethod扩展标准yup验证

现在我们应该导入模块并定义regex

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(),
});

我们在生产中使用了这个示例,效果很好

祝你好运