33. Implementing Client-side Validation using Javascript

PROBLEM

Sometimes it is desirable to validate the end-users input on the browser using javascript.

SOLUTION

The solution is the same for any JSP web application. Embed or Include the javascript validation logic and configure a web control to invoke the validation javascript based on an end-user event.

HOW IT WORKS

Here's an example of a javascript function that can be added to a JSP. The JSP contains a form that needs to be validated. Rather than having a button that submits the form, the form can contain a button that invokes the javascript function, which implements the validation logic. Depending on the results of the validation logic, either the end-user will get an alert of the error or the form will be submitted to the server.

Example 2.37. Sample client-side validation using javascript

<script type="text/javascript" language="javascript"> 
function validateMyForm() { 
if (document.forms[0].idfield.value == "")  
  { 
    alert('ID must not be blank'); 
    return false; 
  } 

document.forms[0].submit(); 
} 
</script>

If you are using the form tags of the Skyway Builder tag library, you can use the Custom Script command on the onclick event of a Skyway button.

Figure 2.22. Event and Commands

Event and Commands

RELATED RECIPES

  1. Validating End-User Input on Server using Spring Validator

  2. Publishing a AJAX service using DWR