我正在尝试用Yup验证电话号码:
phone: Yup.number()
.typeError("That doesn't look like a phone number")
.positive("A phone number can't start with a minus")
.integer("A phone number can't include a decimal point")
.min(8)
.required('A phone number is required'),
Run Code Online (Sandbox Code Playgroud)
.min(8)验证该数字是否为8或更多.所以简单输入8就会通过.如何才能使8个字符需要1000 0000才会通过?
abh*_*ekp 28
我创建了一个yup-phone模块,用于google-libphonenumber提供准确的验证检查,并且可以直接从 github 安装
npm install --save yup yup-phone.
检查使用情况
const Yup = require('yup');
require('yup-phone');
// validate any phone number (defaults to India for country)
const phoneSchema = Yup.string().phone().required();
phoneSchema.isValid('9876543210'); // ? true
Run Code Online (Sandbox Code Playgroud)
从简单的反应验证器,
电话号码验证的正则表达式是
/^(\+?\d{0,4})?\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{4}\)?)?$/
Run Code Online (Sandbox Code Playgroud)
// index.js
const yup = require('yup');
const { rePhoneNumber } = require('./yup-phone')
const schema = yup.string().phone()
const phone = '+911234567890';
console.log('Is Valid? ', rePhoneNumber.test(phone)); // Is Valid? true
schema.validateSync(phone);
Run Code Online (Sandbox Code Playgroud)
// yup-phone.js
const yup = require('yup');
const rePhoneNumber = /^(\+?\d{0,4})?\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{4}\)?)?$/;
module.exports.rePhoneNumber = rePhoneNumber
yup.addMethod(yup.string, "phone", function() {
return this.test("phone", "Phone number is not valid", value =>
rePhoneNumber.test(value)
);
});
Run Code Online (Sandbox Code Playgroud)
小智 21
嗨,现在我解决了和你一样的问题,我找到了可能的解决方案.
使用与Regex匹配的字符串验证电话号码
const phoneRegExp = /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/
phoneNumber: Yup.string().matches(phoneRegExp, 'Phone number is not valid')
Run Code Online (Sandbox Code Playgroud)
您可以搜索不同的正则表达式并进行验证.我在本文中使用了Regex https://www.sitepoint.com/community/t/phone-number-regular-expression-validation/2204
小智 12
const phoneRegExp = /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/
phone_number: Yup.string()
.required("required")
.matches(phoneRegExp, 'Phone number is not valid')
.min(10, "too short")
.max(10, "too long"),Run Code Online (Sandbox Code Playgroud)
这最适合我...你可以设置自己的长度...我只想要 10 位数字不少于或较多
试试这个,它可能对你有帮助。
mobile: Yup.string().matches(/^[6-9]\d{9}$/, {message: "请输入有效号码。", excludeEmptyString: false})