Complete validation with Ajax

Source: Internet
Author: User
Tags date format return string tostring window
Ajax business logic: A standard input box, required to enter the date format of the text, in line with the requirements of the green Word display information, otherwise use the red Word hint.

Page: validation.html

<%@ page contenttype= "text/html; CHARSET=GBK "%>
<title>
Using Ajax for validation
</title>
<script type= "Text/javascript" >
XMLHttpRequest objects
var xmlHttp;

Creating XMLHttpRequest Objects
function Createxmlhttprequest () {
if (window. ActiveXObject) {
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
}
else if (window. XMLHttpRequest) {
XmlHttp = new XMLHttpRequest ();
}
}

Validation method
function Validate () {
Creating objects
Createxmlhttprequest ();
Get Form Date value
var date = document.getElementById ("birthdate");
Submit Address
var url = "validationservlet?birthdate=" + Escape (Date.Value);
Xmlhttp.open ("Get", url,true);
Xmlhttp.onreadystatechange=callback;
Xmlhttp.send (NULL);
}

         //callback methods
           function Callback () {
           if ( Xmlhttp.readystate = = 4) {
            if (xmlhttp.status {
             var mes = XmlHttp.responseXML.getElementsByTagName ("message") [0].firstchild.data;
                                 var val = XmlHttp.responseXML.getElementsByTagName ("passed") [0].firstchild.data;

                                //Set hint information
                                  setmessage (Mes,val);
                        }
                }
         }

Set up a hint information
function Setmessage (message,isvalid) {
var Messagearea = document.getElementById ("Datemessage");
var fontcolor = "Red";
if (IsValid = = "true") {
FontColor = "green";
}

Messagearea.innerhtml= "<font color=" + fontcolor + ">" + message + "</font>";
}
</script>

<body>
Ajax Validation Example
Birth date:<input type= "text" size= "ten" id= "Birthdate"/>
<div id= "Datemessage" ></div>
</body>

Server-side code, performing validation

Validationservlet.java

Import javax.servlet.*;
Import javax.servlet.http.*;
Import java.io.*;
Import java.util.*;
Import Java.text.SimpleDateFormat;

public class Validationservlet extends HttpServlet {
private static final String Content_Type = "text/html;" CHARSET=GBK ";

Initialize Global Variables
public void Init () throws Servletexception {
}

/**
* Process GET Requests
* @param request HttpServletRequest
* @param response HttpServletResponse
* @throws servletexception
* @throws IOException
*/
public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Response.setcontenttype (Content_Type);
Get Output Object
PrintWriter out = Response.getwriter ();

Get the date value as a parameter validation
Boolean passed = Validatedate (Request.getparameter ("birthdate"));
Response.setcontenttype ("Text/xml");
Response.setheader ("Cache-control", "No-cache");
String message = "Your have entered an invalid date.";

if (passed) {
Message = ' You have entered a valid date. '
}

Enter XML format string
Out.println ("<response>");
Out.println ("<passed>" + boolean.tostring (passed) + "</passed>");
Out.println ("<message>" + message + "</message>");
Out.println ("</response>");
Out.close ();
}

Clean up resources
public void Destroy () {
}

/**
* Date of verification
* @param date String
* @return Boolean
*/
Private Boolean validatedate (String date) {
Boolean isValid = true;
if (date!= null) {
SimpleDateFormat formatter = new SimpleDateFormat ("mm/dd/yyyy");
try {
Formatter.parse (date);
}
catch (Exception ex) {
System.out.println (Ex.tostring ());
IsValid = false;
}
}
else{
IsValid = false;
}

return isValid;
}
}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.