Using JavaScript Spring MVC Client Side Validation - javascript

I am new to Spring MVC and JavaScript and I am trying to validate a view using JavaScript (client side). Validation is working, but the problem is, when the error occurs, I am unable to stop form submission. It's going to post method.
How can I stop the submission if error occurs?
My view is registration.jsp
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="<c:url value="/resources/js/j.js" />"></script>
<title>Insert title here</title>
</head>
<body>
<h2>Please,Do Registration</h2>
<form:form id="form" method="POST" action="/spring-ex02/user/reg"
commandName="login" >
<table>
<tr>
<td><form:label path="email">Email</form:label></td>
<td><form:input id="email" path="email" /></td>
<td><font id="emailError" style="color: red;">${emailExistError}
</font></td>
</tr>
<tr>
<td><form:label path="password">Password</form:label></td>
<td><form:input id="password" path="password" type="password"
/></td>
<td><font id="passwordError" style="color: red;">${passwordError}
</font></td>
</tr>
<tr>
<td><form:label path="confirmPassword">Confirm Password</form:label>
</td>
<td><form:input id="confirmPassword" path="confirmPassword"
type="password" /></td>
<td><font id="confirmPasswordError" style="color: red;"></font>
</td>
</tr>
<tr>
<td><form:label path="userDetail.firstname">First Name</form:label>
</td>
<td><form:input id="firstName" path="userDetail.firstname" /></td>
<td><font id="firstNameError" style="color: red;"></font>
</td>
</tr>
<tr>
<td><form:label path="userDetail.lastname">Last Name</form:label>
</td>
<td><form:input id="lastName" path="userDetail.lastname" /></td>
<td><font id="lastNameError" style="color: red;"></font> </td>
</tr>
<tr>
<td><form:label path="userDetail.address">Address</form:label></td>
<td><form:input id="address" path="userDetail.address" /></td>
<td><font id="addressError" style="color: red;"></font> </td>
</tr>
<tr>
<td><form:label path="userDetail.contact">Contact</form:label></td>
<td><form:input id="contact" path="userDetail.contact" /></td>
<td><font id="contactError" style="color: red;"></font>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" onclick="validate()" value="Sign Up"/>
</td>
</tr>
</table>
</form:form>
<form action="/spring-ex02/" method = GET>
<input type="submit" value="Back to Home">
</form>
</body>
</html>
My js file is J.js
function validate(){
var f=document.getElementById("form");
validateEmail(f);
validatePassword(f);
firstNameValidate(f);
lastNameValidate(f)
addressValidate(f);
contactValidate(f)
}
function validateEmail(form){
var error=document.getElementById("emailError");
var email=form["email"].value;
error.innerHTML="";
var regx = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|
(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-
Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if( email==null || email==""){
error.innerHTML="Input Your Email";
}
else if(!email.match(regx)){
error.innerHTML="Invalid Email";
}
}
function validatePassword(form){
var error1=document.getElementById("passwordError");
var error2=document.getElementById("confirmPasswordError");
error1.innerHTML="Give Password";
var password=form["password"].value;
error1.innerHTML="";
error2.innerHTML="";
var confirmPassword=form["confirmPassword"].value;
if( password==null || password==""){
error1.innerHTML="Give Password";
}
else if( confirmPassword==null || confirmPassword==""){
error2.innerHTML="Confirm Password";
}
else if(password.length<5 || password.length>10){
error1.innerHTML="Password has to be 5 to 10 chars"
}
else if(password != confirmPassword){
error2.innerHTML="Password Does Not Match"
}
}
function firstNameValidate(from){
var error=document.getElementById("firstNameError");
var firstName=form["firstName"].value;
error.innerHTML="";
if( firstName==null || firstName==""){
error.innerHTML="Input Your FirstName";
}
else if(!isNaN(id)){
error.innerHTML="Name Can Not be a number";
}
else if(firstName.length<5 || firstName.length>10){
error1.innerHTML="Name has to be 5 to 10 chars"
}
}
function lastNameValidate(from){
var error=document.getElementById("lastNameError");
var lastName=form["lastName"].value;
error.innerHTML="";
if( lastName==null || lastName==""){
error.innerHTML="Input Your LastName";
}
else if(!isNaN(id)){
error.innerHTML="Name Can Not be a number";
}
else if(lastName.length<5 || lastName.length>10){
error1.innerHTML="Name has to be 5 to 10 chars"
}
}
function addressValidate(from){
var error=document.getElementById("addressError");
var address=form["address"].value;
error.innerHTML="";
if( address==null || address==""){
error.innerHTML="Input Your Address";
}
else if(!isNaN(id)){
error.innerHTML="Address Can Not be a number";
}
else if(address.length<5 || address.length>10){
error1.innerHTML="Address has to be 5 to 10 chars"
}
}
function contactValidate(from){
var error=document.getElementById("contactError");
var contact=form["contact"].value;
error.innerHTML="";
if( contact==null || contact==""){
error.innerHTML="Input Your Contact";
}
else if(isNaN(id)){
error.innerHTML="Name Can Not be alphabate";
}
else if(contact.length<5 || contact.length>10){
error1.innerHTML="Contact has to be 5 to 10 chars"
}
}

Problem is your are not cancelling the form submit event.
To cancel form submit, with few changes, try this out.
<input type="submit" onclick="return validate()" value="Sign Up"/> <!-- added `return` -->
Also you need to modify your script as, false return value will cancel the event:
function validate(){
var f=document.getElementById("form");
return (validateEmail(f) &
validatePassword(f) &
firstNameValidate(f) &
lastNameValidate(f) &
addressValidate(f) &
contactValidate(f));
}
You need to modify validation functions as well to return boolean value.
function validateEmail(form){
//your validaton logic
return "" === error.innerHTML;
}
Same has to be done for the rest of the functions

Consolidate your validation methods. On failure use event.preventDefault()

assign return parameter to each of the validation function.
Below is the updated code for J.js
function validate(){
var f=document.getElementById("form");
var hasEmailError = validateEmail(f);
var hasPasswordError = validatePassword(f);
var hasFirstNameError = firstNameValidate(f);
var hasLastNameError = lastNameValidate(f)
var hasAddressError = addressValidate(f);
var hasContactError = contactValidate(f);
if(!hasEmailError || !hasPasswordError || !hasFirstNameError || !hasLastNameError || !hasAddressError || !hasContactError)
return false;
else
return true;
}
function validateEmail(form){
var error=document.getElementById("emailError");
var email=form["email"].value;
error.innerHTML="";
var regx = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|
(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-
Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if( email==null || email==""){
error.innerHTML="Input Your Email";
}
else if(!email.match(regx)){
error.innerHTML="Invalid Email";
}
if(error.innerHTML.length > 0)
return false;
else
return true;
}
function validatePassword(form){
var error1=document.getElementById("passwordError");
var error2=document.getElementById("confirmPasswordError");
error1.innerHTML="Give Password";
var password=form["password"].value;
error1.innerHTML="";
error2.innerHTML="";
var confirmPassword=form["confirmPassword"].value;
if( password==null || password==""){
error1.innerHTML="Give Password";
}
else if( confirmPassword==null || confirmPassword==""){
error2.innerHTML="Confirm Password";
}
else if(password.length<5 || password.length>10){
error1.innerHTML="Password has to be 5 to 10 chars"
}
else if(password != confirmPassword){
error2.innerHTML="Password Does Not Match"
}
if(error1.innerHTML.length > 0 || error2.innerHTML.length > 0)
return false;
else
return true;
}
function firstNameValidate(from){
var error=document.getElementById("firstNameError");
var firstName=form["firstName"].value;
error.innerHTML="";
if( firstName==null || firstName==""){
error.innerHTML="Input Your FirstName";
}
else if(!isNaN(id)){
error.innerHTML="Name Can Not be a number";
}
else if(firstName.length<5 || firstName.length>10){
error.innerHTML="Name has to be 5 to 10 chars"
}
if(error.innerHTML.length > 0)
return false;
else
return true;
}
function lastNameValidate(from){
var error=document.getElementById("lastNameError");
var lastName=form["lastName"].value;
error.innerHTML="";
if( lastName==null || lastName==""){
error.innerHTML="Input Your LastName";
}
else if(!isNaN(id)){
error.innerHTML="Name Can Not be a number";
}
else if(lastName.length<5 || lastName.length>10){
error.innerHTML="Name has to be 5 to 10 chars"
}
if(error.innerHTML.length > 0)
return false;
else
return true;
}
function addressValidate(from){
var error=document.getElementById("addressError");
var address=form["address"].value;
error.innerHTML="";
if( address==null || address==""){
error.innerHTML="Input Your Address";
}
else if(!isNaN(id)){
error.innerHTML="Address Can Not be a number";
}
else if(address.length<5 || address.length>10){
error.innerHTML="Address has to be 5 to 10 chars"
}
if(error.innerHTML.length > 0)
return false;
else
return true;
}
function contactValidate(from){
var error=document.getElementById("contactError");
var contact=form["contact"].value;
error.innerHTML="";
if( contact==null || contact==""){
error.innerHTML="Input Your Contact";
}
else if(isNaN(id)){
error.innerHTML="Name Can Not be alphabate";
}
else if(contact.length<5 || contact.length>10){
error.innerHTML="Contact has to be 5 to 10 chars"
}
if(error.innerHTML.length > 0)
return false;
else
return true;
}

Related

Why I cannot validate User ID?

Here I tried to validate the User Id using JavaScript for a form. But I could not get the expected message. You can see my code below the description. can you help me to find the wrong that I have done?
<html>
<head>
<script>
function formValidation(uid) {
var numbers = /^[0-9]/;
if (uid.value == "") {
alert('Empty values are not allowed.');
return false;
}
else if (numbers.test(uid.value) == false) {
alert('Please input numbers only');
return false;
}
else if (userid_validation(uid, 5, 12) == false) {
return false;
}
else {
return true;
}
}
function userid_validation(uid, mx, my) {
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx) {
alert("length be between " + mx + " to " + my);
return false;
}
else {
return true;
}
}
</script>
</head>
<body>
<form name="form1" onsubmit="return formValidation(this)">
<table>
<tr>
<td>
*Enter valid ID :
</td>
<td>
<input type="text" name="userid"></input>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="Submit" />
</td>
</tr>
</table>
</body>
</form>
</html>
Your uid OBJECT is equal to the form element. To get the input value you need to assign an id for it. and also the RegEx for numbers /^[0-9]/ main that any input starting with number it will return true for (12ABCD). To get only numbers use /^\d+$/ or /^[0-9]+/.
<script>
function formValidation(uid) {
var numbers = /^[0-9]+$/;
if (uid.userid.value == "") {
alert('Empty values are not allowed.');
return false;
}
else if (numbers.test(uid.userid.value) == false) {
alert('Please input numbers only');
return false;
}
return (userid_validation(uid, 5, 12));
}
function userid_validation(uid, mx, my) {
var uid_len = uid.userid.value.length;
if (uid_len >= my || uid_len < mx) {
alert("length be between " + mx + " to " + my);
return false;
}
return true;
}
</script>
I add the id="userid" in input tag.
<form name="form1" onsubmit="return formValidation(this)">
<table>
<tr>
<td>
*Enter valid ID :
</td>
<td>
<input type="text" name="userid" id="userid"></input>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="Submit" />
</td>
</tr>
</table>
</form>

Javascript: validating form fields by regular expression and using if/else statement

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>

Javascript to prevent form post if not validated

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.

Having problems with simple Javascript form validation

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

Resetting Radio Buttons

Here is a fiddle containing my code - http://jsfiddle.net/jamiepollard28/sDLV4/8/
I am trying to make my code reset the radio buttons only when the user clicks cancel on the alert box of validation for the radio buttons.
When you click submt containing the required data with a radio button selected a alert box will come up confirming or rejecting the choice, when i click cancel on that alert box i want the radio button selection to reset.
Below is my code.
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
window.onload=function(){
window.validateForm=function() {
var result = true;
var msg = "";
var focusname="";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
focusname="name";
//document.ExamEntry.name.focus();
document.getElementById('name1').style.color = "red";
//result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
// document.ExamEntry.subject.focus();
if (focusname=="")
{
focusname="subject";
}
document.getElementById('subject1').style.color = "red";
//result = false;
}
var Number = document.ExamEntry.Exam_Number.value
if (Number == "") {
msg += "You must enter the exam Number \n";
//document.ExamEntry.Exam_Number.focus();
if (focusname=="")
{
focusname="Exam_Number";
}
document.getElementById('Exam_Number1').style.color = "red";
//result = false;
}else if (Number.length != 4) {
msg += "You must enter at least Four Numbers in the Exam Number \n";
if (focusname=="")
{
focusname="Exam_Number";
}
//document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number1').style.color = "red";
//result = false;
}
else if (isNaN(Number)) {
msg += "You must enter at least four numeric characters in the Exam Number feild \n";
if (focusname=="")
{
focusname="Exam_Number";
}
// document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number1').style.color = "red";
//result = false;
}
var valchecked = '';
var len = document.getElementsByName('examtype').length;
for (i = 0; i < len; i++) {
if ( document.ExamEntry.examtype[i].checked ) {
valchecked = document.ExamEntry.examtype[i].value;
break;
}
}
if (valchecked == '') {
msg += "Select Exam Type";
document.getElementById('Exam_Type').style.color = "red";
if (focusname=="")
{
focusname="examtype_GCSE";
}
}
if (msg != ""){
alert(msg)
document.getElementById(focusname).focus();
return false;
}else{
return confirm('You have chosen ' + valchecked + ' is this correct?');
}
}
}//]]>
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name1">Name</td>
<td><input type="text" name="name" id="name" /></td>
</tr>
<tr>
<td id="subject1">Subject</td>
<td><input type="text" name="subject" id="subject"/></td>
</tr>
<tr>
<td id="Exam_Number1">Exam Number</td>
<td><input type="text" name="Exam_Number" id="Exam_Number" ><font size="3">(Maximum characters: 4)</font> </td>
</tr>
<tr>
<table><form action="">
<td id="Exam_Type">Exam Type</td>
<tr><td><input type="radio" id="examtype_GCSE" name="examtype" value="GCSE" /> : GCSE<br /></tr>
<tr><td><input type="radio" id="examtype_AS" name="examtype" value="AS"/> : AS<br /></tr>
<tr><td><input type="radio" id="examtype_A2" name="examtype" value="A2" /> : A2<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>
</html>
You are simply returning the users choice, you need to first check it, if it is true return true for form submission else reset radio and return false, as follows: FIDDLE
var ch= confirm('You have chosen ' + valchecked + ' is this correct?');
if(!ch){
document.getElementById('examtype_'+valchecked).checked= false;
return false; }
else
return true;
}
With an if loop you can solve the issue
try following code
if(confirm('You have chosen ' + valchecked + ' is this correct?')){
return true;
}
else{
document.getElementById('examtype_'+valchecked).checked= false;
return false;
}

Categories

Resources