表单验证一直很繁琐,特别是大点的表单,如果每个input都去单独写验证简直要写死人,最近写了一小段js统一的验证表单内容是否正确。
使用这段代码就不再需要对每个input写格式判断,只需要将正确格式的正则表达式写在datatype里就可以了,提交表单按钮也只需要绑定checkform函数就可以了。
大家有什么建议可以评论一下
//表单验证//点击下一步事件function checkform(form){var success = true;$(.+form+ input).each(function(){var $that = $(this);var datatype = eval($that.attr(datatype));if(datatype!=undefined){if($that.val().match(datatype)){$that.removeclass(borderred);}else{$that.focus();$that.addclass(borderred);success = false;return false;}}})return success;}//给每个带有datatype属性的标签绑定blur focus事件$(document).on(blur,input,function(){var $that = $(this);var datatype = eval($that.attr(datatype));if(datatype!=undefined){if($that.val().match(datatype)){$that.removeclass(borderred);}else{$that.addclass(borderred);}}})$(document).on(focus,input,function(){$(this).removeclass(borderred);});
以上内容给大家分享了jquery+正则实现统一的表单验证,希望大家喜欢。