I have the following validation code for a simple form. I am able to perform basic validation but the form still gets posted even if the data is wrong and an alert is generated. How can I stop that from happening?
JS CODE
function validate(){
validateForm();
}
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["pname"].value;
var email = document.forms["myForm"]["email"].value;
var phone = document.forms["myForm"]["phone"].value;
var date = document.forms["myForm"]["date"].value;
var month = document.forms["myForm"]["month"].value;
var year = document.forms["myForm"]["year"].value;
window.load = function() {
var myForm = document.getElementById('myForm');
myForm.onsubmit = function(e) {
return validateForm(); // will be false if the form is invalid
}
}
if (x == null || x == "") {
alert("Name must be filled out");
return false;}
else if (y == null || y == "") {
alert("Address must be filled out");
return false;
}
else if(email == '' || email.indexOf('#') == -1 || email.indexOf('.') == -1)
{
alert("Insert Valid Email Address");
return false;
}
else if(phone == ''|| phone <1000000000 || phone >9999999999){
alert("Enter valid phone number");
return false;
}else if(date =='' || date<01 || date >31){
alert("Enter valid date ");
return false;
}else if(month =='' || month<1 || month >12){
alert("Enter valid month ");
return false;
}else if(year =='' || year<1800 || year >2015){
alert("Enter valid year ");
return false;
}
}
Form
<form name="myForm" action="http://www.randyconnolly.com/tests/process.php" onsubmit="return validate()" method="post">
<table width="30%" border="0" align="center" cellpadding="10" cellspacing="20">
<tr>
<td width="20%"> <span style="font-size: 22px">Name:</span><br>
<br /></td>
<td width="80%"><input type="text" name="fname" required /></td>
</tr>
<tr>
<td><span style="font-size: 22px">Picture Name: <br>
<br></span></td>
<td><input type="text" name="pname" required /></td>
</tr>
<tr>
<td><span style="font-size: 22px">Email:</span> <br>
<br></td>
<td><input type="text" name="email" required /></td>
</tr>
<tr>
<td><span style="font-size: 22px">Phone:</span> <br>
<br></td>
<td><input type="number" name="phone" required /></td>
</tr>
<tr>
<td><span style="font-size: 22px">Date(mm/dd/yyyy):</span></td>
<td><input type="text" name="month" size="2" required />
/
<input type="text" name="date" size="2" required />
/
<input type="text" name="year" size="4" required /></td>
</tr>
<tr>
<td><span style="font-size: 22px">Artwork</span></td>
<td><input type="file" accept="image/gif" name="pic" ></td>
</tr>
</table>
<br><br>
<input class="button-0" type="submit" value="Submit" />
<br>
</form>
You have several issues with your code.
Your validation function needs to return false to prevent the form submission.
You are registering the window.onload handler inside of the validateForm function. Since, the the time the validateForm function is called, the form is already being submitted.
The handler in your markup is validate. Your validate method doesn't return anything so submission won't be prevented by that either.
The easiest way to fix everything would to be to remove the window.onload handler from your code altogether. You could then change validate to:
function validate() {
return validateForm();
}
And submission should be prevented properly.
I got it working. Instead of calling validate() and in that calling validateForm() I directly called validateForm() at the onsubmit. Thanks for the help.
Related
I want the user to enter 2 password and the the password must match, in order to finish the sign up form. I know that there are several question like this and I have try them all out, but none is working. Please help me with this
I have try some coding from the internet but it did not work.
<form method = "POST" action="daftar.php" autocomplete="off">
<center>
<table>
<tr><th>Nama Penuh:</th>
<td><input type="text" name="namapeminjam" size="24"
placeholder="Mohamad Ziqreey" minlength="5" required=""></td>
</tr>
<tr><th>No KP:</th>
<td><input type="text" id="id" name="nokppeminjam" size="24"
minlength="12" maxlength="12" required="" placeholder="Tanpa '-' Atau
Jarak"></td>
</tr>
<tr><th>Kata Laluan:</th>
<td><input type="password" name="katalaluan" size="24"
placeholder="zIqreey#123" minlength="8" maxlength="16" title="Kata Laluan
Anda Perlulah Terdiri Dari Lapan Aksara Mengandungi Sekurang-Kurangnya 1
Huruf Besar Dan Dan Huruf Kecil Termasuk Sekurang-Kurangnya Satu Nombor"
required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" id="idd"></td>
</tr>
<tr><th>Kata Laluan:</th>
<td><input type="password" name="katalaluan2" size="24"
placeholder="zIqreey#123" minlength="8" maxlength="16" title="Kata Laluan
Anda Perlulah Terdiri Dari Lapan Aksara Mengandungi Sekurang-Kurangnya 1
Huruf Besar Dan Dan Huruf Kecil Termasuk Sekurang-Kurangnya Satu Nombor"
required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" id="idd2"></td>
</tr>
</table>
<br><input type="checkbox" onclick="myFunction()">Tunjukkan Kata Laluan
<script>
function myFunction() {
var x = document.getElementById("idd");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
</script>
</center>
<script type="text/javascript">
function validatePasswords()
{
var pass1=document.getElementById("katalaluan").value;
var pass2=document.getElementById("katalaluan2").value;
if(! pass1==pass2)
{
alert("passwords don't match");
return false;
}
return true;
}
</script>
<br><br>
<center><input id="buttonon" type ="submit" name="daftarpengguna"
value="DAFTAR" onclick="return validatePasswords();"/>
</center>
</form>
You are trying to find the inputs by their name using the getElementById function. You need to pass in the Id instead to the function.
Second, the if statement isn't formatted correctly. The explanation mark should be next to the equals sign.
function validatePasswords()
{
var pass1 = document.getElementById("idd").value;
var pass2 = document.getElementById("idd2").value;
if(pass1 != pass2)
{
alert("passwords don't match");
return false;
}
return true;
}
In my program I have created form and fields in form. I am trying to validate fields. For that I have used regular expression though my regular expression is correct but regular expression for phone doesn't execute. Can anyone tell me wether I defined if/else statement for validation correctly ?
code:
function validateForm() {
var zip = document.myform.zip;
var email = document.myform.email;
var phone = document.myform.phone;
if (email.value == "") {
window.alert("Please enter email Address.");
state.focus();
return false;
}
var regEx2 = /^[0-9]{5}(?:-[0-9]{4})?$/;
if (zip.value.match(regEx2)) {
return true;
} else {
window.alert("Please provide a zip in the ##### or #####-#### format.");
zip.focus();
return false;
}
var regEx = /^(?:\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}$/;
if (phone.value.match(regEx)) {
return true;
} else {
window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");
phone.focus();
return false;
}
}
<form name="myform" id="myform" action="" onsubmit="return validateForm()" method="post">
<table cellspacing="2" cellpadding="2" border="0">
<tr>
<td align="right">Zip</td>
<td><input type="text" name="zip" maxlength="15" size="28" /></td>
</tr>
<tr>
<td align="right">Telephone number</td>
<td><input type="text" name="phone" size="28" placeholder="(555) 555-5555" /></td>
</tr>
<tr>
<td align="right"> EMail </td>
<td> <input type="text" name="email" size="28" /></td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /> </td>
</tr>
</table>
The problem is here -
if (zip.value.match(regEx2)) {
return true;
} else {
window.alert("Please provide a zip in the ##### or #####-#### format.");
zip.focus();
return false;
}
You are returning from this point regardless of valid or invalid zip. Code blocks afterward won't get executed.
I would suggest not to return in every successful if block, because, the code execution will return from that point without validating the other fields.
function validateForm() {
var valid = true;
var zip = document.myform.zip;
var email = document.myform.email;
var phone = document.myform.phone;
if (email.value == "")
{
window.alert("Please enter email Address.");
email.focus();
valid = false;
}
var regEx2 = \^[0-9]{5}(?:-[0-9]{4})?$\;
if(!zip.value.match(regEx2))
{
window.alert( "Please provide a zip in the ##### or #####-#### format." );
zip.focus() ;
valid = false;
}
var regEx = \^(?:\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}$\;
if(!phone.value.match(regEx))
{
window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");
phone.focus();
valid = false;
}
return valid;
}
if you really want to validate one field only when all the previous fields are valid (as your current code), this is working -
function validateForm() {
var zip = document.myform.zip;
var email = document.myform.email;
var phone = document.myform.phone;
if (email.value == "")
{
window.alert("Please enter email Address.");
email.focus();
return false;
}
var regEx2 = \^[0-9]{5}(?:-[0-9]{4})?$\;
if(!zip.value.match(regEx2))
{
window.alert( "Please provide a zip in the ##### or #####-#### format." );
zip.focus() ;
return false;
}
var regEx = \^(?:\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}$\;
if(!phone.value.match(regEx))
{
window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");
phone.focus();
return false;
}
return true;
}
Here is the complete script -
<!DOCTYPE html>
<html>
<head>
<title>NumerValidation</title>
</head>
<body>
<form name="myform" id="myform" action="" onsubmit="return validateForm();" method="post">
<table cellspacing="2" cellpadding="2" border="0">
<tr>
<td align="right">Zip</td>
<td><input type="text" name="zip" maxlength="15" size="28"/></td>
</tr>
<tr>
<td align="right">Telephone number</td>
<td><input type="text" name="phone" size="28" placeholder="(555) 555-5555"/></td>
</tr>
<tr>
<td align="right"> EMail </td>
<td> <input type="text" name="email" size="28" /></td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit"/> </td>
</tr>
</table>
</form>
<script>
function validateForm() {
var zip = document.myform.zip;
var email = document.myform.email;
var phone = document.myform.phone;
if (email.value == "")
{
window.alert("Please enter email Address.");
email.focus();
return false;
}
var regEx2 = /^[0-9]{5}(?:-[0-9]{4})?$/;
if(!zip.value.match(regEx2))
{
window.alert( "Please provide a zip in the ##### or #####-#### format." );
zip.focus() ;
return false;
}
var regEx = /^(?:\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}$/;
if(!phone.value.match(regEx))
{
window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");
phone.focus();
return false;
}
return true;
}
</script>
</body>
</html>
I have a script here that is supposed to run when triggered. However, it will only work if the variable passwd is not used in my if else statements.
NEWLY UPDATED JS:
function validateForm() {
var name = document.forms["myForm"]["name"].value;
var phone = document.forms["myForm"]["phone"].value;
var email = document.forms["myForm"]["email"].value;
var add = document.forms["myForm"]["address"].value;
var passwd = document.forms["myForm"]["password"].value;
var matchesCount = email.split("#").length - 1;
var matchesCount2 = email.split(".").length - 1;
var error = "";
if (!name || !phone || !email || !add || !passwd) {
error+="All must be filled out \n"
if(phone.search(/^[0-9]*$/) == -1 || phone.length != 8){
error+="- Phone number can only contain digits \n";}
if(passwd.search(/^[0-9a-zA-Z]*$/) == -1){
error+="- Password needs to be alphanumeric \n";
}
if(passwd.length <8 || passwd.length > 16){
error+="- Password contain only 8-16 digits \n";
}
if(matchesCount > 1 || matchesCount2 < 1){
error+="- Please enter a valid email \n";
}
alert(error);
return false;
}
}
HTML
<div id="newaccount">
<table id="tablenewuser">
<form name="myForm" action="ControllerServlet" onsubmit="return validateForm()" method="post">
<tr>
<td class="newusertd">Name:<span class="price">*</span></td>
<td class="newusertd"><input style="color: black;" type="text" name="name" class="Btn"></td>
</tr>
<tr>
<td class="newusertd">Contact Number:<span class="price">*</span></td>
<td class="newusertd"><input style="color: black;" type="text" name="phone" placeholder="98989898"class="Btn"></td>
</tr>
<tr>
<td class="newusertd">Email:<span class="price">*<br></span></td>
<td class="newusertd"><input style="color: black;" type="text" name="email" placeholder="xxx#hello.com" class="Btn"></td>
</tr>
<tr>
<td class="newusertd">Address:<span class="price">*</span></td>
<td class="newusertd"><input style="color: black;" type="text" name="address" class="Btn"></td>
</tr>
<tr>
<td class="newusertd">Password:<span class="price">*</span><br>(8-16 Characters with<br>one UPPERCASE & numbers)</td>
<td class="newusertd"><input style="color: black;" type="password" name="password" class="Btn">
</tr>
<tr>
<td class="newusertd"></td>
<td class="newusertd">
<input style="color: black;" type="submit" value="Create Account" class="Btn"/></td>
</tr>
</form>
</table>
</div>
(Sorry for the mess!)
EDIT: The script works but the the password is not working as it should be. Please see the comments
Quick glance shows at least 2 problems with that area:
passwd could be null and pass through the outer if condition. Attempting length on it would cause an error
You may want to wrap the inner conditionals in an else block
if (name == null || name == "" || phone == null || phone == "" || email == null || email == "" || add == null || add == ""
|| passwd == null || passwd == "") {
error+="All must be filled out \n";
} else {
// other conditions
}
if (error) alert(error);
In JS, it's passwd.length not length()
You should use the JS console to verify what errors are appearing.
I see the problem, .length is a property, not a method. Your length check should be:
if (passwd.length >= 8 && passwd.length <= 16) {
error += "- Only 8-16 digits \n";
}
One more note, foo == null || foo == "" can be simplified to !foo as null and "" are both falsy values in JS.
Im not expert but i recommend you evaluate mail field with regex (/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/) and i created a separated function for validate each of the values in the form for add a text error, then another validation who evaluate if all the fiels pass the evaluation, like yours but i made it liek that: if(validateName(nameVar) && validateEmail(emailVar) this is all the code that i made, that validate a correct form mail, a name with alphabetical form and phone without null value:
function validateName(nameVar) {
var nameReg = /^[a-zA-Z'.\s]{1,40}$/;
return nameReg.test(nameVar);
}
function validateEmail(emailVar) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(emailVar);
}
function email() {
var nameVar = $('#name').val();
var emailVar = $('#email').val();
var phoneVar = $('#phone').val();
var messageVar = $('#message').val();
if(!validateName(nameVar) ) {
console.log("dentro");
$('#nameError').text("Por favor ingresa un nombre valido");
}else{
$('#nameError').text("");
}
if(!validateEmail(emailVar) || emailVar == "") {
$('#emailError').text("Por favor ingresa un correo valido");
}else{
$('#emailError').text("");
}
if(phoneVar == "") {
$('#phoneError').text("Por favor ingresa un número telefonico");
}else{
$('#phoneError').text("");
}
if(validateName(nameVar) && validateEmail(emailVar) && emailVar != "" && phoneVar != ""){
var data = {};
data.name = nameVar;
data.email = emailVar;
data.phone = phoneVar;
data.message = messageVar;
//here your validate code with array of values ready for doing something
}
};
and this is the html code:
<h4 class="title-yellow contacto" id="title-yellow">Envianos un mensaje</h4>
<div class="row"> </div>
<div class="row">
<div class="col-md-6 form-group">
<input class="form-control" id="name" name="nombre" placeholder="Nombre" type="text" required >
</div>
<div class="col-md-6 form-group">
<input class="form-control" id="email" name="email" placeholder="Email" type="email" required >
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<input class="form-control" id="phone" name="telefono" placeholder="Teléfono" type="tel" required >
</div>
</div>
<textarea class="form-control" id="message" name="mensaje" placeholder="Mensaje" rows="4">
</textarea>
<br>
<div class="row">
<div class="col-md-12 form-group">
<button class="email nohover pull-right" id="mail" onclick="email()">ENVIAR</button>
<p id="demo"></p>
<div id="nameError"></div>
<div id="emailError"></div>
<div id="phoneError"></div>
<div id="ajaxMessage"></div>
</div>
</div>
I'm having trouble validating my form. When the form is submitted i have onsubmit="return validateInput();". If the user Enters no data the function validateInput() works correctly, changing the HTML and displaying the messages I want. But I am also trying to call function goodNum() and function checkCreditCard().
function goodNum() is ment to check that the phone number a user entered is correct, not just random numbers.
function checkCreditCard() serves the same purpose goodNum() but for a credit card.
The problem is that as long as the user enters any data into all the fields in the form it will submit. I am new to javascript and haven spent hours trying to work this out and am still clueless, any help would be greatly appreciated.
JAVASCRIPT
`
var validation = false;
function validateInput()
{
var valid = new Boolean(true);
if(validation == false)
{
alert("Please choose the Pizza size to order");
valid = false;
}
if(document.getElementById('customer_name').value == "")
{
alert("You must enter your name");
document.getElementById('customer_name').style.background='red';
valid = false;
}
if( document.getElementById('email').value == "")
{
alert("Please enter your E-mail");
document.getElementById('email').style.background='red';
valid = false;
}
if( document.getElementById('mobile_num').value == "")
{
alert("Please enter your phone number");
document.getElementById('mobile_num').style.background='red';
valid = false;
}
else if(!goodNum()){
alert("The number you entered is incorrect");
document.getElementById('mobile_num').style.background='red';
valid = false;
}
if( document.getElementById('credit_card').value == "")
{
alert("Please enter your credit card number");
document.getElementById('credit_card').style.background='red';
valid = false;
}
else if(!checkCreditCard())
{
alert("The credit card number you entered is incorrect");
document.getElementById('credit_card').style.background='red';
valid = false;
}
if( document.getElementById('customer_address').value == "")
{
alert("Please enter your Address");
document.getElementById('customer_address').style.background='red';
valid = false;
}
return valid;
}
//checks the phone number the user entered
function goodNum()
{
var num;
num = document.forms["myForm"]["mobileNum"].value;
var valid = new Boolean(true);
if((num==null) || (num==" "))
{
valid= false;
}
if(num.length != 10)
{
valid = false;
}
var a = num.slice(2,3);
if (!((a=="3") || (a=="5") || (a=="6") || (a=="7")))
{
valid=false;
}
for(index=3;index<10;index++)
{
a = num.slice(index,index+1);
if((a< "0") || (a> "9"))
valid =false;
}
var count = 0;
for (n=0;n<9;n++)
{
a = num.slice(n,n+1);
if((c == "0") || (c == "2") || (c == "4") || (c == "6") || (c == "8"))
count = count+1;
}
var b = parseInt(mobilenum.slice(9,10), 10);
if (!(b == count))
{
valid=false;
}
if(!valid)
{
alert("Re-enter your number.");
}
return valid;
}
//checking to make sure the user entered a correct credit card number
//using the luhn formula
function checkCreditCard()
{
var valid = new Boolean(true);
var cardNum;
cardNum = document.forms["myForm"]["creditCard"].value;
var cNum = 0, checkNumber=0;
if (cardNum.length != 16)
{
valid=false;
}
for(var x = cardNum.length - 1; x >= 0; x--)
{
checkNumber = cardNum.charAt(x);
checkNumber = parseInt(checkNumber, 10);
if((x%2) == 0)
{
checkNumber = checkNumber*2;
if(checkNumber > 9)
{
checkNumber = checkNumber -9;
}
}
cNum += checkNumber;
}
if(!(cNum%10)==0)
{
valid = false;
}
return valid;
}
HTML
<form name="myForm" onsubmit="return validateInput();" id="customer_details" method="get" action="http://atlantis.cit.ie/displayvalues.php">
<fieldset>
<legend>Choose Your Pizza: </legend>
<table>
<tr>
<td colspan="3">
<img src="base.png" id="base" width="150" height="150" alt="base" />
<img src="anchovies.png" id="anchovies" width="150" height="150" alt="anchovies" />
<img src="cheese.png" id="cheese" width="150" height="150" alt="cheese" />
<img src="onions.png" id="onions" width="150" height="150" alt="Pizza" />
<img src="p4.png" id="pizh" width="150" height="150" alt="Pizza" />
<img src="pepperoni.png" id="pepperoni"width="150" height="150" alt="Pepperoni" />
<img src="olives.png" id="olives" width="150" height="150" alt="olives" />
</td>
</tr>
<tr>
<td><input type="radio" id="radio1" onclick="resize();validation=true;" name="pbase" value="small" /> Small</td>
<td><input type="radio" id="radio2" onclick="resize();validation=true;" name="pbase" value="medium" /> Medium</td>
<td><input type="radio" id="radio3" onclick="resize();validation=true;" name="pbase" value="large" /> Large</td>
</tr>
<tr>
<td colspan="2">Anchovies</td>
<td><input type="checkbox" id="Anchovies" name="anch" onclick="doVisible()" value="0.50" /></td>
</tr>
<tr>
<td colspan="2">Cheese</td>
<td><input type="checkbox" id="Cheese" name="ch" onclick="doVisible()" value="0.50" /></td>
</tr>
<tr>
<td colspan="2">Onions</td>
<td><input type="checkbox" id="Onions" name="oni" onclick="doVisible()" value="0.50" /></td>
</tr>
<tr>
<td colspan="2">Pepper</td>
<td><input type="checkbox" id="pepper" name="pe" onclick="doVisible()" value="0.50" /></td>
</tr>
<tr>
<td colspan="2">Pepperoni</td>
<td><input type="checkbox" id="Pepperoni" name="pep" onclick="doVisible()" value="0.50" /></td>
</tr>
<tr>
<td colspan="2">Olives</td>
<td><input type="checkbox" id="Olive" name="ol" onclick="doVisible()" value="0.50" /></td>
</tr>
<tr>
<td colspan="2">Name:*</td>
<td><input type="text" id="customer_name" name="customerName" size="35" placeholder="John Doe" /></td>
</tr>
<tr>
<td colspan="2">Email Address:*</td>
<td><input type="text" id="email" name="emailAdd" size="35" placeholder="example#mycit.ie"/></td>
</tr>
<tr>
<td colspan="2"> Phone Number:*</td>
<td><input type="text" id="mobile_num" name="mobileNum" size="35" placeholder="0851111111" /></td>
</tr>
<tr>
<td colspan="2">Credit Card Number:*</td>
<td><input type="text" id="credit_card" name="creditCard" size="35" /></td>
</tr>
<tr>
<td colspan="2">Address:*</td>
<td><textarea id="customer_address" name="address" rows="5" cols="27"></textarea></td>
</tr>
<tr>
<td colspan="3"><input value="Order Now" onclick="" type="submit" /><input value="Reset Order" onclick="" type="Reset" /></td>
</tr>
</table>
</fieldset>
</form>
`
(that isn't all the code, i have other functions that work so I don't think they are causing the problem, also, sorry for so much code)
You have two problems in the following code:
var count = 0;
for (n=0;n<9;n++)
{
a = num.slice(n,n+1);
if((c == "0") || (c == "2") || (c == "4") || (c == "6") || (c == "8"))
count = count+1;
}
var b = parseInt(mobilenum.slice(9,10), 10);
ashould be c
mobilenum is not defined
When these two problems are corrected, your message "Re-enter your number" is displayed.
I have a suggestion as well. Since you are a beginner and this code is probably critical to the business you are working for, you should consider using a validation library. You can find a review at: https://www.codefellows.org/blog/the-ten-best-javascript-libraries-for-form-validation-and-formatting
I am currently doing a GCSE course which allows me to ask for assistance from IT sources as long as I reference them in my investigation. I wish to make the following code validate that there is a number of four digits in the Examination Number entry field. I'm okay with simple validation but this is another step for me.
<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.examnumber.value=="") {
msg+="You must enter your Examination Number \n";
document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color="red";
result = false;
}
var checked = null;
var inputs = document.getElementsByName('examtype');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
document.getElementById('examtype').style.color="red";
}
}
if(checked==null)
{
msg+="Please choose an option";
result = false;
}
else{
confirm("You have chosen "+checked.value+" is this the correct course?");
}
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>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examnumber">Examination Number</td>
<td><input type="text" name="examnumber" /></td>
</tr>
<tr>
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
</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>
Regarding checking if it is number, you can use some regex:
e.g.
var reg = /^\d{4}$/ig;
var regExRes = reg.exec(document.ExamEntry.examnumber.value);
if (document.ExamEntry.examnumber.value == "" || (regExRes == null || regExRes.length == 0)) {
msg += "You must enter your Examination Number \n";
document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color = "red";
result = false;
}
To avoid entering anything beside number, I would suggest you to use something like jquery pluging called masked input
EDIT:
line changed from var reg = /\d{4}/ig; to var reg = /^\d{4}$/ig;