Home >Web Front-end >JS Tutorial >jquery regular implementation of unified form validation_jquery
Form verification has always been very cumbersome, especially for larger forms. If you write separate verification for each input, it will be a death blow. Recently, I wrote a short piece of js to uniformly verify whether the form content is correct.
Using this code, you no longer need to write format judgment for each input. You only need to write the correct format of the regular expression in the datatype. The submit form button only needs to be bound to the checkForm function.
If you have any suggestions, please comment
<input type="text" datatype=“正则”/> //表单验证 //点击下一步事件 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"); });
The above content has shared with you how to implement unified form validation using jquery regularity. I hope you like it.