// regexChecks.js
// 邮箱校验
const emailRegex = /^[^\s@]+@[^\s@]+.[^\s@]+$/;
// 手机号码校验(中国地区)
const mobileRegex = /^1[3-9]\d{9}$/;
// 身份证号码校验(中国地区)
// 或者/^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/
const idCardRegex = /^(?:\d{15}|\d{17}[\dX])$/;
// 密码校验(8-20位,至少一个数字、一个字母、一个特殊字符)
const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,20}$/;
// URL 校验
const urlRegex = /^(https?://)[^\s/$.?#].[^\s]*$/;
// 正整数格式校验规则
const INTEGER_POSITIVE = /^\d+$/;
// 校验中文名
const validChineseName = /^(?:[\u4e00-\u9fa5·]{2,16})$/;
// 用于检查小数(最多两位小数)。
const INTEGER_FLOAT =
/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
// 固定电话格式校验规则(如 `021-12345678`)
const TELEPHONE= new RegExp(/^(\d{3,4}-)\d{7,8}$/);
// 用于验证时间段格式(如 `09:00-18:00`)
const VALIDTIME =
/^([0-1]?[0-9]|2[0-3]):([0-5][0-9])-([0-1]?[0-9]|2[0-3]):([0-5][0-9])$/;
// 用于校验名称的字符(支持中文、字母、特殊字符等)
const NAME_CHARACTER =
/^[\w|\-|/|\\|[|\]|(|)|\u4e00-\u9fff|\uff08|\uff09|\u3010|\u3011]*$/;
// 用于检测输入中是否含有不允许的特殊字符
const LABEL =
/[`~!@#$%^&*()_+=<>?:"{}|,;'\\[\]·~!@#¥%……&*()——+={}|《》?:“”【】、;‘',。、]/im;
// 检查值范围
const PRIORITY_RANGE = /^[0-9999]$/;
// 根据给定的正则表达式进行校验
function validate(input, regex) {
return regex.test(input);
}
// 示例用法
const testEmail = "example@example.com";
const testMobile = "13812345678";
const testIdCard = "123456789012345";
const testPassword = "Password1!";
const testUrl = "http://www.example.com";
console.log(`邮箱校验: ${validate(testEmail, emailRegex)}`); // true
console.log(`手机号码校验: ${validate(testMobile, mobileRegex)}`); // true
console.log(`身份证号码校验: ${validate(testIdCard, idCardRegex)}`); // true
console.log(`密码校验: ${validate(testPassword, passwordRegex)}`); // true
console.log(`URL 校验: ${validate(testUrl, urlRegex)}`); // true
在这个示例中,定义了一些常见的正则表达式进行验证,包括邮箱、手机号码、身份证号码、密码和URL的校验。也提供了一个 validate
函数来验证输入是否符合给定的正则表达式。可以用于表单输入的合法性检查,提高用户输入的准确性和系统的稳定性。