一个jQuery-validation实例
文章目录
主要内容就是写了一个很简陋的HTML页面,上面有一个表单,然后提交给Servlet,Servlet返回表单输入的内容(用户名和密码)。 稍微有点成就感的是用了jQuery-validation来进行表单的验证,所以直接把代码贴在这里备忘。
ServletSample.java
{% codeblock lang:java %} package koi;
import java.io.IOException; import java.io.PrintWriter;
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import org.apache.jasper.tagplugins.jstl.core.Out;
import com.sun.org.apache.xml.internal.serialize.Printer;
/**
-
Servlet implementation class ServletSample */ @WebServlet(description = “Just another servlet sample.", urlPatterns = { “/ServletSample” }) public class ServletSample extends HttpServlet { private static final long serialVersionUID = 1L;
/**
- @see HttpServlet#HttpServlet() */ public ServletSample() { super(); // TODO Auto-generated constructor stub }
/**
-
@see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub
response.getWriter().append(“Served at: “).append(request.getContextPath()); }
/**
-
@see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append(request.getParameter(“username”)).append(request.getParameter(“password”));
doGet(request, response); }
}
{% endcodeblock %}
login.html
注意jQuery-validation文件的路径,我这里把文件放在桌面了。
{% codeblock lang:html %}
</body>
rules.js
规则js代码如下: {% codeblock lang:javascript %} $.validator.setDefaults({ submitHandler: function() { myform.submit(); alert(“submitted!"); } });
$().ready(function() { // validate signup form on keyup and submit $("#myform”).validate({ rules: { username: { required: true, minlength: 2 }, password: { required: true, minlength: 5 } }, messages: { username: { required: “Please enter a username”, minlength: “Your username must consist of at least 2 characters” }, password: { required: “Please provide a password”, minlength: “Your password must be at least 5 characters long” } } }); }); {% endcodeblock %}