HTML:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js实现:‘w5-8‘ -> /^\w{5,8}$/</title> <style> body{padding: 100px;} .abs{position: absolute;} .rel{position: relative;} .inp{height: 30px;line-height: 30px;text-indent: 5px;width: 200px;} .error{color: red;left: 0;top: 40px;} .zoom{clear: both;} .mb40{margin-bottom: 40px;} .btn{display: block;width: 100px;height: 40px;line-height: 40px;text-align: center;color: #fff;background-color: orange;text-decoration: none;} </style> </head> <body> <div class="rel zoom mb40"> <input type="text" class="inp" data-type="w5-8" data-error="请填写5-8位包括下划线的任何单词字符"> <div class="error abs"></div> </div> <div class="rel zoom mb40"> <input type="text" class="inp" data-type="w10-12" data-error="请填写10-12位包括下划线的任何单词字符"> <div class="error abs"></div> </div> <script src="v1.js"></script> <script src="test.js"></script> </body> </html>
JS:
$(function () { bindW($(‘.inp‘)); function bindW(obj) { $.each(obj, function () { var my = $(this), error = my.siblings(‘.error‘), type = my.data(‘type‘), pattern=/^[A-Za-z]+/,//匹配到第一个字符串返回数组 zm = type.match(pattern),//获取到第一个字母 index1 = type.match(eval("/"+zm+"/")),//字母的index index2 = type.match(/(\-)/),//中划线的index num1 = type.substring(index1.index+1,index2.index), num2 = type.substring(index2.index+1), str = ‘/^\\‘+ zm +‘{‘+ num1 +‘,‘+ num2 +‘}$/‘; //执行验证 my.on({ focus : function () { error.text(‘‘); }, blur : function () { var val = my.val(), flag = val.match(eval(str)); if (!flag) { var errorVal = my.data(‘error‘); // alert(0); error.text(errorVal); } } }); }); } });
js实现:'w5-8' -> /^\w{5,8}$/
时间: 2024-10-18 14:53:38