Hello i have a JSP page that contain a form, i want to validate the form data like date of birth format and value, breed id – zoo id that are numbers only and animals name that exist
here is my JSP page:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.ArrayList" %>
<%@page import="content.*"%>
<%@ page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
<title>Append Animal</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Zoo keeper</th></tr>
</table>
<h1>Append Animal</h1>
<form name="insert" action="Relay" >
<fieldset>
Animal new name: <input type= "text" name = "aname"><br>
Animal new DOB: <input type= "text" name = "dob"><br>
Animal new gender:
<select name="gender" id="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
Animal status:
<select name="source" id="source">
<option value="born">Born</option>
<option value="bought">Bought</option>
</select>
<br>
Animal old zoo: <input type= "text" name = "zooid" > only if bought<br>
Animal new Breed: <input type= "text" name = "breedid" ><br>
Animal new remarks: <textarea name = "remark" rows="4" cols="20">
</textarea> <br /> <br/>
<input type="submit" value="submit">
<input type="hidden" name="command" value="AppendAnimalServlet" >
</fieldset>
</form>
</body></html>
i added this script in JSP page:
<script>
function validateForm()
{
if(document.insert.aname.value ==="")
{
alert("Animal should have a name");
document.insert.aname.focus();
return false;
}
if(document.insert.zooid.value !=="")
{
if (! (/^\d*(?:\.\d{0,2})?$/.test(document.insert.zooid.value))) {
alert("Please enter a valid Zoo id");
document.insert.zooid.focus();
return false;
}
}
if(document.insert.breedid.value !=="")
{
if (! (/^\d*(?:\.\d{0,2})?$/.test(document.insert.breedid.value))) {
alert("Please enter a valid Breed id");
document.insert.breedid.focus();
return false;
}
}
if(document.insert.dob.value ==="")
{
alert("Animal should have a date of birth");
document.insert.aname.focus();
return false;
}
}
</script>
but i don’t think i’m doing this right any suggestion on how to deal with this ?
and please note that the form values will be transfared to a Relay servlet to handle the insert process
<form name="insert" action="Relay" onsubmit="return validateForm();">
A validation library can be built using some generic code like the following (just a quick example, it can be extended greatly):
And some HTML