Validating Information Has Been Input - javascript

I was just wondering if anyone was able to help me with a JavaScript validation routine, Im trying to make it so that the Exam ID Number gets validated after information has been submit, So far all that is needed is name and subject and it will allow the examiner to proceed through without entering the exam ID number, Can anyone help me with this.
<script language="javascript"" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter your Exam ID Number \n";
document.ExamEntry.subject.focus();
document.getElementById('Exam Number').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
<style type="text/css">
h1,h2,h3,h4,h5,h6 {
font-family: "Comic Sans MS";
}
</style>
<h1>Exam Entry Form</h1>
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr> <tr>
<td id="Exam Number">Exam ID Number</td>
<td><input type="Number" name="ID Number"maxlength="4" > </td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>

Here is the full html
<html>
<head>
<script type="text/javascript">
function validateForm() {
var result = true;
var msg = "";
if (document.getElementById("txtname").value == "") {
msg += "You must enter your name \n";
document.getElementById("name").focus();
document.getElementById('name').style.color = "red";
result = false;
}
if (document.getElementById("txtsubject").value == "") {
msg += "You must enter the subject \n";
document.getElementById("subject").focus();
document.getElementById('subject').style.color = "red";
result = false;
}
if (document.getElementById("ID_Number").value == "") {
msg += "You must enter your Exam ID Number \n";
document.getElementById("ID_Number").focus();
document.getElementById('Exam Number').style.color = "red";
result = false;
}
if (msg == "") {
return result;
}
else {
alert(msg)
return result;
}
}
</script>
</head>
<body>
<form id="ExamEntry">
<h1>
Exam Entry Form</h1>
<table width="50%" border="0">
<tr>
<td id="name">
Name
</td>
<td>
<input type="text" id="txtname" />
</td>
</tr>
<tr>
<td id="subject">
Subject
</td>
<td>
<input type="text" id="txtsubject" />
</td>
</tr>
<tr>
<td id="Exam Number">
Exam ID Number
</td>
<td>
<input type="Number" id="ID_Number" maxlength="4">
</td>
</tr>
<tr>
<td>
<input type="submit" name="Submit" value="Submit" onclick="return validateForm();" />
</td>
<td>
<input type="reset" name="Reset" value="Reset" />
</td>
</tr>
</table>
</form>
</body>
</html>

Related

JSP page form validation: 2 forms and 2 scripts

I have two forms in my JSP page which should be validated by two embedded JS scripts (see code below). The trouble is that the scripts don't work properly and omit validating the first entries (username and loginName respectively). I had two external Javascript files to do the validation but that had a similar problem.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Scotia Login Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<!-- <script type="text/javascript" src="scripts/stafflogin.js"></script> -->
<!--<script type="text/javascript" src="scripts/userlogin.js"></script> -->
<link rel="stylesheet" type="text/css" href="styles/DWBA.css"/>
</head>
<body>
<div class="outer">
<div class="header"><h1>Scotia Island & Wildlife Cruises</h1></div>
<div class="box"><h2>Login Page</h2>
<script>
function validateform1() {
var username = document.stafflogin.username.value;
var password = document.stafflogin.password.value;
if (username === null || username === "") {
alert("Please enter the admin username");
document.stafflogin.username.focus();
return false;
} else if (password === null || password === "") {
alert("Please enter the admin password");
document.stafflogin.password.focus();
return false;
}
}
</script>
<form name="stafflogin" action="CustomerServlet" onsubmit="return validateform1()"><!-- -->
<h3>Staff Login with username and password</h3>
<p> To login, enter details below:</p>
<table cellspacing="8" border="0">
<tr>
<td align="left"><p>Staff Username:</p></td><!-- USERNAME is admin -->
<td><input type="text" name="username" id="username" /></td>
</tr>
<tr>
<td align="left"><p>Staff Password:</p></td><!-- PASSWORD is admin -->
<td><input type="password" name="password" id="password" /></td>
</tr>
<tr>
<td align="left"><input type="submit" value="stafflogin" name="submit" style="width:75px" /></td>
<td><br /><input type="hidden" name="username" value="" /></td>
</tr>
</table>
</form>
<br />
<script>
function validateform2() {
var name = document.userlogin.loginName.value;
var password = document.userlogin.loginPasswd.value;
if (name === null || name === "") {
alert("Please enter your username");
document.userlogin.loginName.focus();
return false;
} else if (password === null || password === "") {
alert("Please enter your password");
document.userlogin.loginPasswd.focus();
return false;
}
}
</script>
<form name="userlogin" method="POST" action="LoginServlet" onsubmit="return validateform2()">
<h3>Customer Login with login name and login password</h3>
<p> To login, enter details below:</p>
<table cellspacing="8" border="0">
<tr>
<td align="left"><p>Login name:</p></td><!-- -->
<td><input type="text" name="loginName" id="loginName"/></td>
</tr>
<tr>
<td align="left"><p>Login password:</p></td><!-- -->
<td><input type="password" name="loginPasswd" id="loginPasswd"/></td>
</tr>
<tr>
<td align="left"><input type="submit" value="userlogin" name="submit" style="width:75px" /><br /></td>
<td><input type="hidden" name="loginName" value="" /></td>
</tr>
</table>
</form>
<br />
<form name="Form" action="CustomerServlet">
<h3>New Customer registration</h3>
<p>To register, click on "register" below:</p>
<table cellspacing="8" border="0">
<tr>
<td><input type="submit" value="register" name="submit" style="width:75px" /></td>
</tr>
</table>
</form>
</div>
<div class="footer"><div align="center"><!-- ALIGNS EVERYTHING WITHIN DIV -->
<p>© Copyright Scotia Island & Wildlife Cruises, Harbour Road, Morar, Invernessshire.</p>
<form>
<tr>
<td><input type="submit" value="home" name="submit" style="width:75px" /></td>
</tr><br />
</form></div>
</div><br />
</div>
</body>
</html>
As I am a novice at Javascript I need some help to work out why two separate forms and validation scripts won't work as expected. (I have other JSP pages with single external Javascript validation scripts and they all work as intended).
Can anyone suggest a solution?
The answer is to remove the hidden inputs from each form eg.
<input type="hidden" name="username" value="" />
and
<input type="hidden" name="loginName" value="" />
so the forms look like this:
<script type='text/javascript'>
function validateform1() {
'use strict';
var username = document.stafflogin.username.value;
var password = document.stafflogin.password.value;
if (username === null || username === "") {
alert("Please enter the admin username");
document.stafflogin.username.focus();
return false;
} else if (password === null || password === "") {
alert("Please enter the admin password");
document.stafflogin.password.focus();
return false;
} else {
document.stafflogin.submit();
}
}
</script>
<form name="stafflogin" action="CustomerServlet" onsubmit="return validateform1()">
<h3>Staff Login with username and password</h3>
<p> To login, enter details below:</p>
<table cellspacing="8" border="0">
<tr>
<td align="left"><p>Staff Username:</p></td>
<td><input type="text" name="username" id="username" required /></td>
</tr>
<tr>
<td align="left"><p>Staff Password:</p></td>
<td><input type="password" name="password" id="password" /></td>
</tr>
<tr>
<td align="left"><input type="submit" value="stafflogin" name="submit" style="width:75px" /></td>
</tr>
</table>
</form>
and this:
<script type='text/javascript'>
function validateform2() {
'use strict';
var name = document.userlogin.loginName.value;
var password = document.userlogin.loginPasswd.value;
if (name === null || name === "") {
alert("Please enter your username");
document.userlogin.loginName.focus();
return false;
} else if (password === null || password === "") {
alert("Please enter your password");
document.userlogin.loginPasswd.focus();
return false;
} else {
document.userlogin.submit();
}
}
</script>
<form name="userlogin" method="POST" action="LoginServlet" onsubmit="return validateform2()">
<h3>Customer Login with login name and login password</h3>
<p> To login, enter details below:</p>
<table cellspacing="8" border="0">
<tr>
<td align="left"><p>Login name:</p></td>
<td><input type="text" name="loginName" id="loginName"/></td>
</tr>
<tr>
<td align="left"><p>Login password:</p></td>
<td><input type="password" name="loginPasswd" id="loginPasswd"/></td>
</tr>
<tr>
<td align="left"><input type="submit" value="userlogin" name="submit" style="width:75px" /><br /></td>
</tr>
</table>
</form>
In short there was nothing wrong with the Javascript.

Alert not showing up in my html code

I have all of my validation code figured
out but I'm not quite sure on how to code an
alert to pop up before the form is submitted
but after the validation is complete. Pretty
much my alerts which fields have errors, and
what the errors are aren't showing up when
I submit this form. All it is direct me to the
submit successful page despite errors.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<script>
function validateForm() {
var fName = document.forms["orderForm"].firstName.value;//first name validation
if(fName==null || fName=="")
{
document.getElementById('firstNameError').innerHTML= "Please enter a first name.";
return false;
}
var lName = document.forms["orderForm"].lastName.value;//last name validation
if(lName==null || lName=="")
{
document.getElementById('lastNameError').innerHTML= "Please enter a last name.";
return false;
}
var address = document.forms["orderForm"].address.value;//address validation
if(address==null || address=="")
{
document.getElementById('addressError').innerHTML= "Please enter an address.";
return false;
}
var city = document.forms["orderForm"].city.value;//city validation
if(city==null || city=="")
{
document.getElementById('cityError').innerHTML= "Please enter a city.";
return false;
}
var pCodeCheck = /^[0-9a-zA-Z]+$/;//postal code validation
if(postalCode.value.match(pCodeCheck))
{
//do nothing
return true;
}
else
{
document.getElementById('postalCoderror').innerHTML= "Please enter a valid postal code.";
return false;
}
// makes sure you cannot order a negative number of items
var itemQTY = document.forms["orderForm"].widget1qty.value;
if(itemQTY < 0)
{
document.getElementById('qtyError').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY2 = document.forms["orderForm"].widget2qty.value;
if(itemQTY2 < 0)
{
document.getElementById('qtyError2').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY3 = document.forms["orderForm"].widget3qty.value;
if(itemQTY3 < 0)
{
document.getElementById('qtyError3').innerHTML= "You cannot enter a negative number.";
return false;
}
//makes sure there is at least one item ordered
var wid1Qty = document.getElementById('widget1qty').value;
var wid2Qty = document.getElementById('widget2qty').value;
var wid3Qty = document.getElementById('widget3qty').value;
if(wid1Qty + wid2Qty + wid3Qty == 0)
{
document.getElementById('itemQTY').innerHTML= "You must order atleast one item.";
return false;
}
var total1;
var total2;
var total3;
var total4;
total1 = document.forms['orderForm']['widget1qty'].value * 5;
total2 = document.forms['orderForm']['widget2qty'].value * 15;
total3 = document.forms['orderForm']['widget3qty'].value * 25;
total4 = (total1 + total2 + total3)
alert('Your total is: $' + total4 + '.00');
return;
}
function startValidate(){
validateForm();
document.forms['orderForm'].submit();
}
</script>
<div id="wrapper">
<h2 class="center">Order Form</h2> <!-- action="processForm.html" "javascript:void(0)" -->
<form name="orderForm" method="post" onsubmit="validate();" action="processForm.html">
<fieldset>
<legend>Personal Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td><span class="required">*</span>First Name:</td>
<td><input type="text" name="firstName" id="firstName" size="30"></td>
<td id="firstNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Last Name:</td>
<td><input type="text" name="lastName" id="lastName" size="30"></td>
<td id="lastNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Address:</td>
<td><input type="text" name="address" id="address" size="30"></td>
<td id="addressError"></td>
</tr>
<tr>
<td><span class="required">*</span>City:</td>
<td><input type="text" name="city" id="city" size="30"></td>
<td id="cityError"></td>
</tr>
<tr>
<td><span class="required">*</span>Province:</td>
<td><select name="province" id="province" size="1">
<option disabled>Select a province</option>
<option value="BC">British Columbia</option>
<option value="AB">Alberta</option>
<option value="SK">Saskatchewan</option>
<option value="MB">Manitoba</option>
<option value="ON">Ontario</option>
<option value="QC">Québec</option>
<option value="NB">New Brunswick</option>
<option value="NS">Nova Scotia</option>
<option value="PE">Prince Edward Island</option>
<option value="NF">Newfoundland</option>
<option value="YK">Yukon</option>
<option value="NWT">Northwest Territories</option>
<option value="NU">Nunavut</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td><span class="required">*</span>Postal Code:</td>
<td><input type="text" name="postalCode" id="postalCode" maxlength="6"></td>
<td id="postalCoderror"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Order Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td rowspan="3">Select your products:<br>
<td>Widget #1
<input type="text" name="widget1qty" id="widget1qty" size="1" value="0">Qty # <strong>$5.00/ea</strong></td>
<td id="qtyError"></td>
</tr>
<tr>
<td>Widget #2
<input type="text" name="widget2qty" id="widget2qty" size="1" value="0">Qty # <strong>$15.00/ea</strong></td>
<td id="qtyError2"></td>
</tr>
<tr>
<td>Widget #3
<input type="text" name="widget3qty" id="widget3qty" size="1" value="0">Qty # <strong>$25.00/ea</strong></td>
<td id="qtyError3"></td>
</tr>
<tr>
<td rowspan="3"></td>
<td></td>
<td id="itemQTY"></td>
</tr>
<tr></tr><tr></tr><tr></tr>
<tr>
<td rowspan="3">Shipping Type:</td>
<td>Standard ($5.00)<input type="radio" name="shippingType" id="shippingTypeStandard" value="Standard" checked></td>
</tr>
<tr>
<td>Express ($10.00)<input type="radio" name="shippingType" id="shippingTypeExpress" value="Express"></td>
</tr>
<tr>
<td>Overnight ($20.00)<input type="radio" name="shippingType" id="shippingTypeOvernight" value="Overnight"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Submit Order</legend>
<table>
<tr>
<th colspan="2"></th>
</tr>
<tr>
<input type="submit" name="btnSubmit" id="btnSubmit" onsubmit="startValidate()" value="Submit Order">
<td><input type="reset" name="btnReset" id="btnReset" value="Reset Form"></td>
</tr>
</table>
</fieldset>
</form>
</div>
</body>
This is what I would do:
HTML:
<body>
<div id="wrapper">
<h2 class="center">Order Form</h2> <!-- action="processForm.html" "javascript:void(0)" -->
<form name="orderForm" method="post" action="processForm.html" onsubmit="return startValidate()">
<fieldset>
<legend>Personal Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td><span class="required">*</span>First Name:</td>
<td><input type="text" name="firstName" id="firstName" size="30"></td>
<td id="firstNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Last Name:</td>
<td><input type="text" name="lastName" id="lastName" size="30"></td>
<td id="lastNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Address:</td>
<td><input type="text" name="address" id="address" size="30"></td>
<td id="addressError"></td>
</tr>
<tr>
<td><span class="required">*</span>City:</td>
<td><input type="text" name="city" id="city" size="30"></td>
<td id="cityError"></td>
</tr>
<tr>
<td><span class="required">*</span>Province:</td>
<td><select name="province" id="province" size="1">
<option disabled>Select a province</option>
<option value="BC">British Columbia</option>
<option value="AB">Alberta</option>
<option value="SK">Saskatchewan</option>
<option value="MB">Manitoba</option>
<option value="ON">Ontario</option>
<option value="QC">Québec</option>
<option value="NB">New Brunswick</option>
<option value="NS">Nova Scotia</option>
<option value="PE">Prince Edward Island</option>
<option value="NF">Newfoundland</option>
<option value="YK">Yukon</option>
<option value="NWT">Northwest Territories</option>
<option value="NU">Nunavut</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td><span class="required">*</span>Postal Code:</td>
<td><input type="text" name="postalCode" id="postalCode" maxlength="6"></td>
<td id="postalCoderror"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Order Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td rowspan="3">Select your products:<br>
<td>Widget #1
<input type="text" name="widget1qty" id="widget1qty" size="1" value="0">Qty # <strong>$5.00/ea</strong></td>
<td id="qtyError"></td>
</tr>
<tr>
<td>Widget #2
<input type="text" name="widget2qty" id="widget2qty" size="1" value="0">Qty # <strong>$15.00/ea</strong></td>
<td id="qtyError2"></td>
</tr>
<tr>
<td>Widget #3
<input type="text" name="widget3qty" id="widget3qty" size="1" value="0">Qty # <strong>$25.00/ea</strong></td>
<td id="qtyError3"></td>
</tr>
<tr>
<td rowspan="3"></td>
<td></td>
<td id="itemQTY"></td>
</tr>
<tr></tr><tr></tr><tr></tr>
<tr>
<td rowspan="3">Shipping Type:</td>
<td>Standard ($5.00)<input type="radio" name="shippingType" id="shippingTypeStandard" value="Standard" checked></td>
</tr>
<tr>
<td>Express ($10.00)<input type="radio" name="shippingType" id="shippingTypeExpress" value="Express"></td>
</tr>
<tr>
<td>Overnight ($20.00)<input type="radio" name="shippingType" id="shippingTypeOvernight" value="Overnight"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Submit Order</legend>
<table>
<tr>
<th colspan="2"></th>
</tr>
<tr>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit Order">
<td><input type="reset" name="btnReset" id="btnReset" value="Reset Form"></td>
</tr>
</table>
</fieldset>
</form>
</div>
</body>
JS:
<script>
function validateForm() {
var errors = 0;
var fName = document.forms["orderForm"].firstName.value;//first name validation
if (fName == null || fName == "")
{
document.getElementById('firstNameError').innerHTML = "Please enter a first name.";
errors++;
} else {
document.getElementById('firstNameError').innerHTML = "";
}
var lName = document.forms["orderForm"].lastName.value;//last name validation
if (lName == null || lName == "")
{
document.getElementById('lastNameError').innerHTML = "Please enter a last name.";
errors++;
} else {
document.getElementById('lastNameError').innerHTML = "";
}
var address = document.forms["orderForm"].address.value;//address validation
if (address == null || address == "")
{
document.getElementById('addressError').innerHTML = "Please enter an address.";
errors++;
} else {
document.getElementById('addressError').innerHTML = "";
}
var city = document.forms["orderForm"].city.value;//city validation
if (city == null || city == "")
{
document.getElementById('cityError').innerHTML = "Please enter a city.";
errors++;
} else {
document.getElementById('cityError').innerHTML = "";
}
var pCodeCheck = /^[0-9a-zA-Z]+$/;//postal code validation
if (postalCode.value.match(pCodeCheck))
{
document.getElementById('postalCoderror').innerHTML = "";
}
else
{
document.getElementById('postalCoderror').innerHTML = "Please enter a valid postal code.";
errors++;
}
// makes sure you cannot order a negative number of items
var itemQTY = document.forms["orderForm"].widget1qty.value;
if (itemQTY < 0)
{
document.getElementById('qtyError').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError').innerHTML = "";
}
var itemQTY2 = document.forms["orderForm"].widget2qty.value;
if (itemQTY2 < 0)
{
document.getElementById('qtyError2').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError2').innerHTML = "";
}
var itemQTY3 = document.forms["orderForm"].widget3qty.value;
if (itemQTY3 < 0)
{
document.getElementById('qtyError3').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError3').innerHTML = "";
}
//makes sure there is at least one item ordered
var wid1Qty = document.getElementById('widget1qty').value;
var wid2Qty = document.getElementById('widget2qty').value;
var wid3Qty = document.getElementById('widget3qty').value;
if (wid1Qty + wid2Qty + wid3Qty == 0)
{
document.getElementById('itemQTY').innerHTML = "You must order atleast one item.";
errors++;
} else {
document.getElementById('itemQTY').innerHTML = "";
}
var total1;
var total2;
var total3;
var total4;
total1 = document.forms['orderForm']['widget1qty'].value * 5;
total2 = document.forms['orderForm']['widget2qty'].value * 15;
total3 = document.forms['orderForm']['widget3qty'].value * 25;
total4 = (total1 + total2 + total3);
alert('Your total is: $' + total4 + '.00');
return errors;
}
function startValidate() {
var errors = validateForm();
if (errors == 0) {
document.forms['orderForm'].submit();
} else {
return false;
}
}
</script>
you need to have
<form name="orderForm" method="post" onsubmit="return validate();">
than
<form name="orderForm" method="post" onsubmit="validate();">
The "return" part of it makes sure javascript returns the true/false value and does whatever necessary action is needed
and also in your script try having a one boolean variable that acts as a control so that for example "valid" if 9/10 are correct, the boolean value valid will be false and then the form will not submit.
Example below
function validateForm() {
var valid = new Boolean(true);
//code here - example
var fName = document.forms["orderForm"].firstName.value;//first name validation
if(fName==null || fName=="")
{
valid = false;
document.getElementById('firstNameError').innerHTML= "Please enter a first name.";
return false;
}
return valid
}
There is no use of startValidate function. Just remove that.
your form tag should be <form name="orderForm" method="post" onsubmit="return validateForm();" action="processForm.html">
Use this as submit button, <input type="submit" name="btnSubmit" id="btnSubmit" value="Submit Order"> //<- removed onsubmit="startValidate()" as this is not required.
Most important, just validate your HTML before posting here.
Use onsubmit="startValidate();"
<form name="orderForm" method="post" onsubmit="startValidate();" action="processForm.html">
You can simply use the jQuery Validate plugin as follows.
jQuery:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
});
HTML:
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
When you call startValidate() it will kick off the document.forms.submit line whether or not the validateForm() returns true or false. You need to only submit the form if validateForm() returns true. A false return in your validator won't kill the startValidate() function like you are thinking it will.
Try moving the document.forms['orderForm'].submit(); up into the bottom of your validateForm() method after you've checked all the inputs.

HTML/JS Validation

How can I expand the javascript code so that the examination number can only have a maximum length of 4 digits entered and the user cannot type anymore. Also how can I expand the code so that the examination field isn't left out. Aswell for the radio buttons I want to add a validation so if someone checks any box e.g GCSE a message will come up saying you have ticked (radio button ticked)
Thanks in advance
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="name">Examination number</td>
<td><input type="text" name="Examination number" /></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
<p> Please select <b>ONE</b> button.</br>
<input type="radio" name="group1" value="GCSE">GCSE<br>
<input type="radio" name="group1" value="AS" checked>AS<br>
<input type="radio" name="group1" value="A2" checked>A2<br>
</body>
</html>
<html>
<head>
<title>Success message</title>
</head>
<body>
<H1> You entered all the data required </H1>
</body>
</html>
You can use maxlength:
<input type="text" id="test" name="test" maxlength="4"/>
or in JavaScript you can do this:
Example
var input = document.getElementById("test");
input.oninput = function(){
if (input.value.length > 4)
{
var str = input.value;
str = str.substring(0, str.length - 1);
input.value = str;
alert("Some error message here");
}
}
<input type="text" name="Examination number" maxlength="4"/> for maxlength
put this in form onsubmit="return validateForm();"
check this for javascript validation
http://www.w3schools.com/js/js_form_validation.asp
learn yourself.

Javascript alert not fired

For some reason my java script is changing the colour of the text but not showing my error message, any help would be greatful!
The code is a simple HTML form that asks for examiners name, number, subject and also has some radio buttons
<HTML>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if (document.ExamEntry.ExaminationNumber.value=="") {
msg+="You must enter the Examination Number \n";
document.ExamEntry.ExaminationNumber.focus();
document.getElementById('Examination Number').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="S:\codes\success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
<title>Exam entry</title>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="Examination Number">ExaminationNumber</td>
<td><input type="text" name="Examination Number" /></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<tr>
<td><input type="reset" name="Reset" value="Reset" /></td>
<input type="radio" name="qualification" value="GCSE">GCSE<br>
<input type="radio" name="qualification" value="AS">AS<br>
<input type="radio" name="qualification" value="A2">A2<br>
</form>
</tr>
</table>
</body>
</HTML>
IDs cannot have spaces.. Change Examination Number to something like Examination_Number or ExaminationNumber
Fixed jsFiddle example

Redirect simple HTML page using JavaScript

I am performing JavaScript validation on a simple HTML page. On error I am trying to redirect the page to Error.html, using window.location.href="Error.html".
I get the JavaScript pop displaying the error but page doesn't redirect.
JS:
function checkifFormIsFilled() {
var txtUserName = document.getElementById("txtUserName").value;
var txtFirstName = document.getElementById("txtFirstName").value;
var txtLastName = document.getElementById("txtLastName").value;
var txtEmail = document.getElementById("txtEmail").value;
var txtArea = document.getElementById("txtArea").value;
var errMessage = "";
var errorInForm = false;
if (txtUserName === "") {
errMessage = "UserName";
errorInForm = true;
}
if (txtFirstName === "") {
errMessage += ", First Name";
errorInForm = true;
}
if (txtLastName === "") {
errMessage += ", Last Name";
errorInForm = true;
}
if (txtEmail === "") {
errMessage += ", Email";
errorInForm = true;
}
if (txtArea === "") {
errMessage += ", Address";
errorInForm = true;
}
if (errorInForm == true) {
errMessage += " are required fields";
window.alert(errMessage);
//window.location.href = "Error.html";
window.navigate("Error.html");
}
}
HTML:
<form method="post" style="width: 560px; height: 850px; margin-left: 10px; margin-top:10px">
<fieldset>
<legend>New User</legend>
<table>
<tr>
<td>
<label>User Name:</label></td>
<td>
<input type="text" id="txtUserName" name="User Name" onblur="checkRequired(this)" maxlength="10" /></td>
</tr>
<tr>
<td>
<label>First Name:</label></td>
<td>
<input type="text" id="txtFirstName" name="First Name" maxlength="10" onblur="checkRequired(this)" /></td>
</tr>
<tr>
<td>
<label>Last Name:</label></td>
<td>
<input type="text" id="txtLastName" name="Last Name" maxlength="10" onblur="checkRequired(this)" /></td>
</tr>
<tr>
<td>
<label>Email: </label>
</td>
<td>
<input type="text" name="emailInput" id="txtEmail" onblur="checkRequired(this)" /></td>
</tr>
<tr>
<td>
<label for="lblAddress">Address</label></td>
<td>
<textarea id="txtArea" name="txtAddress" cols="50" rows="5" maxlength="1000" onblur="checkRequired(this)"></textarea></td>
</tr>
<tr>
<td>Groups</td>
<td>
<select name="selGroups">
<option value="c1">Employee</option>
<option value="c1">HR</option>
<option value="c1">Director</option>
</select>
</td>
</tr>
<tr>
<td>Status</td>
<td>
<select name="selStatus">
<option value="c1">Active</option>
<option value="c2">Inactive</option>
</select>
</td>
</tr>
<tr>
<td>
<input id="btnSubmit" value="Add User" type="submit" onclick="checkifFormIsFilled();" />
</td>
<td>
<button id="btnCancel">Cancel</button>
</td>
</tr>
</table>
</fieldset>
</form>
This should do:
if (errorInForm == true) {
errMessage += " are required fields";
window.alert(errMessage);
window.location = "Error.html";
}
Put the function call in an onsubmit attribute on the form element instead. You may also have to return false as well, if an error was found, to prevent it from going to the same page instead of your error page.
Try this:
<input id="btnSubmit" value="Add User" type="button" onclick="checkifFormIsFilled();" />
Since the form was submitting to itself, the redirect wasn't occurring.
DEMO

Categories

Resources