jQuery表单验证功能实例

这里使用jquery实现的表单验证效果,以Ajax方式验证你的表单是否填写正确,如果验证不通过,会将表单元素背景变成红色,并给出提示信息,简单实用,jquery表单验证功能已经有很多了,本款表单验证特效看上去更简单,不懂Ajax的朋友,或许直接套用即可实现无刷新表单验证功能。

运行效果截图如下:

jQuery表单验证功能实例

在线演示地址如下:

具体代码如下:

<!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>jQuery表单验证</title> <style type="text/css"> body, input, textarea { font-size:12px; line-height:18px; font-family:Verdana, Geneva, sans-serif; } input {width:200px;} .submit {width:120px;} #error { color:red; font-size:10px; display:none; } .needsfilled { background:red; color:white; } </style> <script type="text/javascript" src="https://www.jb51.net/jquery-1.6.2.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ // Place ID's of all required fields here. required = ["name", "email", "message"]; // If using an ID other than #email or #error then replace it here email = $("#email"); errornotice = $("#error"); // The text to show up within a field when it is incorrect emptyerror = "Please fill out this field."; emailerror = "Please enter a valid e-mail."; $("#theform").submit(function(){ //Validate required fields for (i=0;i<required.length;i++) { var input = $('#'+required[i]); if ((input.val() == "") || (input.val() == emptyerror)) { input.addClass("needsfilled"); input.val(emptyerror); errornotice.fadeIn(750); } else { input.removeClass("needsfilled"); } } // Validate the e-mail. if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) { email.addClass("needsfilled"); email.val(emailerror); } //if any inputs on the page have the class 'needsfilled' the form will not submit if ($(":input").hasClass("needsfilled")) { return false; } else { errornotice.hide(); return true; } }); // Clears any fields in the form when the user clicks on them $(":input").focus(function(){ if ($(this).hasClass("needsfilled") ) { $(this).val(""); $(this).removeClass("needsfilled"); } }); }); </script> </head> <body> <form action="mail.php" method="post"> <p><label for="name">Name</label><br /><input type="text" value="" /></p> <p><label for="email">E-mail</label><br /><input type="text" value="" /></p> <p><label for="message">Message</label><br /><textarea rows="7" cols="30"></textarea></p> <p><input type="submit" value="Submit Form" /></p> <p>表单中有错误信息!</p> </form> </body> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wggjxx.html