document.bgColor="#FFFFCC";
var myForm = document.getElementById("form"); //declare variables and page styling
var Div1 = document.getElementById("div1");
var Div2 = document.getElementById("div2");
myForm.style.color="blue";
myForm.style.fontSize="20px";
myForm.style.fontWeight="400";
myForm.style.fontFamily="arial";
function validateForm() //form validation
{
var firstname = document.getElementById("firstname"); //declared variables
var lastname = document.getElementById("lastname");
var postcode = document.getElementById("postcode");
var email = document.getElementById("email");
var cardtype = document.getElementById("cardtype");
var cardnumber = document.getElementById("cardnumber");
var ccv = document.getElementById("ccv");
var month = document.getElementById("month");
var year = document.getElementById("year");
if (firstname.value==""){ //validate first name
alert("Your first name can not be left blank");
firstname.focus();
return false;
}
if (lastname.value==""){ //validate last name
alert("Your last name can not be left blank");
lastname.focus();
return false;
}
if (postcode.value.length!=4 || (isNaN(document.getElementById("postcode").value))){ //vaildate post code
alert("Please enter a valid post code");
postcode.focus();
return false;
}
if (email.value.length<5 || email.value.indexOf("#")== -1){ //validate email
alert("Please enter a valid email");
email.focus();
return false;
}
if (email.value.indexOf(".")== -1){
alert("Please enter a valid email");
email.focus();
return false;
}
if (cardnumber.length!=16 || (isNaN(document.getElementById("cardnumber").value))){ //validate card number length
alert("Please enter a valid card number");
cardnumber.focus();
return false;
}
if (ccv.length<3 || (isNaN(document.getElementById("ccv").value))){ //validate ccv number length
alert("Please enter a valid ccv");
ccv.focus();
return false;
}
}
function checkDate(){ //check expiry date of card
var date = new Date();
var month = date.getMonth()+1; //get current month
var year = date.getYear()+1; //get current year
var expiryMonth = document.getElementById("month").value;
var expiryYear = document.getElementById("year").value;
if (month == expiryMonth)//check if the current month has not expired
{
alert("Your card has expired");
month.focus();
return false;
}
if (year == expiryYear) //check if the current year has not expired
{
alert("Your card has expired");
year.focus();
return false;
}
return false;//so the data is not cleared
}
alert("Your order has been successfully submitted thank you"); //notify user of correct submission
return true;
//open up help window
function Popup(){
window.open( "file:///C:/Users/Andy2411/Desktop/4JSB/assignment/html/help.html", "myWindow",
"status = 1, height = 500, width = 500, resizable = 0" );
return;
}
form{width:700px;margin:0 auto;}
#Div1{float:;width:300;height:300;border:2px solid;border-radius:10px;padding:10px;padding-bottom:20px;background-color:;box-shadow:0 0 10px #2DADAC;position: relative; top: -10%; transform: translateY(10%);}
#Div2{float:;width:300;height:300;border:2px solid;border-radius:10px;padding:10px;background-color:;box-shadow:0 0 10px #2DADAC;position: relative; top: -10%; transform: translateY(10%);}
#Div3{text-align:center;margin:0 auto;display:;position: relative; top: -180%; transform: translateY(180%);}
<!DOCTYPE html>
<html>
<!--Pseudocode
INPUT firstname, lastname, postcode, email, cardtype, cardnumber, ccv, expiryMonth, expiryYear
onsubmit = DO validateForm()
END
MODULE validateForm()
IF (firstname =="") THEN
OUTPUT error in firstname
RETURN false
ENDIF
IF (lastname =="") THEN
OUTPUT error in lastname
RETURN false
ENDIF
IF (postcode.length<4 || (isNaN(document.getElementById("postcode").value))) THEN
OUTPUT error in postcode
RETURN false
ENDIF
IF (email.value.length<5 || email.value.indexOf("#", ".")== -1) THEN
OUTPUT error in email
RETURN false
ENDIF
IF (cardnumber.length!=16 || (isNaN(document.getElementById("cardnumber").value))) THEN
OUTPUT error in cardnumber
RETURN false
ENDIF
IF (ccv.length !=3 || (isNaN(document.getElementById("ccv").value))) THEN
OUTPUT error in ccv
RETURN false
ENDIF
IF (month == expiryMonth) THEN
OUTPUT error in month
RETURN false
ENDIF
IF (year == expiryYear) THEN
OUTPUT error in year
RETURN false
ENDIF
OUTPUT correct
RETURN true
END validateForm()-->
<head>
<title>Assignment4JSB</title>
<link rel="stylesheet" type="text/css" href="../css2/assignment.css" />
</head>
<body>
<form name=”userForm” autocomplete="on" id="form" onsubmit="return validateForm()" onsubmit="return checkDate()">
<script src="../js2/assignment.js"></script>
<div id="Div1">
<h2>Order Form</h2>
<fieldset>
<legend>Enter your Details here</legend></br>
<table>
<tr>
<td><label for="firstname">First Name</label></td>
<td><input type="text" name="First_Name" id="firstname" size="30" required="required" autofocus /></td>
</tr>
<tr>
<td><label for="Last_Name">Last Name</label></td>
<td><input type="text" name="Last_Name" id="lastname" size="30" required="required" /></td>
</tr>
<tr>
<td><label for="postcode">Postcode</label></td>
<td><input type="text" name="postcode" id="postcode" size="4" required="required" /></td>
</tr>
<tr>
<td><label for="email">Email</label></td>
<td><input type="text" name="email" id="email" size="30"/></td>
</tr>
</table>
</fieldset>
<h2>Payment Details</h2>
<fieldset>
<legend>Please enter your payment details</legend><br/>
Credit Card <select id="cardtype" required="required">
<option value=""></option>
<option value="Mastercard">Mastercard</option>
<option value="Visa">Visa</option>
<option value="AmericanExpress">American Express</option>
</select>
<br/><br/>
Card number <input type="text" id="cardnumber" size="16" required="required"/>
<br/></br>
CCV <input type="text" size="3" required="required"/>
<br/></br>
Expiry MM/YY <select id="month" required="required">
<option value=""></option>
<option value="month">01</option>
<option value="month">02</option>
<option value="month">03</option>
<option value="month">04</option>
<option value="month">05</option>
<option value="month">06</option>
<option value="month">07</option>
<option value="month">08</option>
<option value="month">09</option>
<option value="month">10</option>
<option value="month">11</option>
<option value="month">12</option>
</select>
<select required="required" id="year">
<option value=""></option>
<option value="year">2016</option>
<option value="year">2017</option>
<option value="year">2018</option>
<option value="year">2019</option>
<option value="year">2020</option>
<option value="year">2021</option>
<option value="year">2022</option>
<option value="year">2023</option>
<option value="year">2024</option>
<option value="year">2025</option>
<option value="year">2026</option>
</select>
</fieldset>
</div>
<br/>
<div id="Div3">
<button type="submit">Submit</button>
<button type="button" onClick="Popup()">Help</button><br/>
</div>
</form>
</body>
</html>
This is an assignment for javascript basic where I have to write a form and validate user input from text boxes and drop down boxes including a date check for the credit card, I have written the code but having difficulty and can't see where I am going wrong, any help would be appreciated.
You've lots off mistakes :
You can use onsubmit attribute on time in element
Return statement always under a function
document.bgColor="#FFFFCC";
var myForm = document.getElementById("form"); //declare variables and page styling
var Div1 = document.getElementById("div1");
var Div2 = document.getElementById("div2");
myForm.style.color="blue";
myForm.style.fontSize="20px";
myForm.style.fontWeight="400";
myForm.style.fontFamily="arial";
function validateForm() //form validation
{
debugger;
var firstname = document.getElementById("firstname"); //declared variables
var lastname = document.getElementById("lastname");
var postcode = document.getElementById("postcode");
var email = document.getElementById("email");
var cardtype = document.getElementById("cardtype");
var cardnumber = document.getElementById("cardnumber");
var ccv = document.getElementById("ccv");
var month = document.getElementById("month");
var year = document.getElementById("year");
if (firstname.value==""){ //validate first name
alert("Your first name can not be left blank");
firstname.focus();
return false;
}
if (lastname.value==""){ //validate last name
alert("Your last name can not be left blank");
lastname.focus();
return false;
}
if (postcode.value.length!=4 || (isNaN(document.getElementById("postcode").value))){ //vaildate post code
alert("Please enter a valid post code");
postcode.focus();
return false;
}
if (email.value.length<5 || email.value.indexOf("#")== -1){ //validate email
alert("Please enter a valid email");
email.focus();
return false;
}
if (email.value.indexOf(".")== -1){
alert("Please enter a valid email");
email.focus();
return false;
}
if (cardnumber.length!=16 || (isNaN(document.getElementById("cardnumber").value))){ //validate card number length
alert("Please enter a valid card number");
cardnumber.focus();
return false;
}
if (ccv.length<3 || (isNaN(document.getElementById("ccv").value))){ //validate ccv number length
alert("Please enter a valid ccv");
ccv.focus();
return false;
}
}
function checkDate(){ //check expiry date of card
var date = new Date();
var month = date.getMonth()+1; //get current month
var year = date.getYear()+1; //get current year
var expiryMonth = document.getElementById("month").value;
var expiryYear = document.getElementById("year").value;
if (month == expiryMonth)//check if the current month has not expired
{
alert("Your card has expired");
month.focus();
return false;
}
if (year == expiryYear) //check if the current year has not expired
{
alert("Your card has expired");
year.focus();
return false;
}
return false;//so the data is not cleared
}
//open up help window
function Popup(){
window.open( "file:///C:/Users/Andy2411/Desktop/4JSB/assignment/html/help.html", "myWindow",
"status = 1, height = 500, width = 500, resizable = 0" );
return;
}
form{width:700px;margin:0 auto;}
#Div1{float:;width:300;height:300;border:2px solid;border-radius:10px;padding:10px;padding-bottom:20px;background-color:;box-shadow:0 0 10px #2DADAC;position: relative; top: -10%; transform: translateY(10%);}
#Div2{float:;width:300;height:300;border:2px solid;border-radius:10px;padding:10px;background-color:;box-shadow:0 0 10px #2DADAC;position: relative; top: -10%; transform: translateY(10%);}
#Div3{text-align:center;margin:0 auto;display:;position: relative; top: -180%; transform: translateY(180%);}
<form name=”userForm” autocomplete="on" id="form" onsubmit="return validateForm();checkDate();">
<script src="../js2/assignment.js"></script>
<div id="Div1">
<h2>Order Form</h2>
<fieldset>
<legend>Enter your Details here</legend></br>
<table>
<tr>
<td><label for="firstname">First Name</label></td>
<td><input type="text" name="First_Name" id="firstname" size="30" autofocus /></td>
</tr>
<tr>
<td><label for="Last_Name">Last Name</label></td>
<td><input type="text" name="Last_Name" id="lastname" size="30" /></td>
</tr>
<tr>
<td><label for="postcode">Postcode</label></td>
<td><input type="text" name="postcode" id="postcode" size="4" /></td>
</tr>
<tr>
<td><label for="email">Email</label></td>
<td><input type="text" name="email" id="email" size="30"/></td>
</tr>
</table>
</fieldset>
<h2>Payment Details</h2>
<fieldset>
<legend>Please enter your payment details</legend><br/>
Credit Card <select id="cardtype" >
<option value=""></option>
<option value="Mastercard">Mastercard</option>
<option value="Visa">Visa</option>
<option value="AmericanExpress">American Express</option>
</select>
<br/><br/>
Card number <input type="text" id="cardnumber" size="16" />
<br/></br>
CCV <input type="text" size="3" />
<br/></br>
Expiry MM/YY <select id="month" >
<option value=""></option>
<option value="month">01</option>
<option value="month">02</option>
<option value="month">03</option>
<option value="month">04</option>
<option value="month">05</option>
<option value="month">06</option>
<option value="month">07</option>
<option value="month">08</option>
<option value="month">09</option>
<option value="month">10</option>
<option value="month">11</option>
<option value="month">12</option>
</select>
<select id="year">
<option value=""></option>
<option value="year">2016</option>
<option value="year">2017</option>
<option value="year">2018</option>
<option value="year">2019</option>
<option value="year">2020</option>
<option value="year">2021</option>
<option value="year">2022</option>
<option value="year">2023</option>
<option value="year">2024</option>
<option value="year">2025</option>
<option value="year">2026</option>
</select>
</fieldset>
</div>
<br/>
<div id="Div3">
<button type="submit">Submit</button>
<button type="button" onClick="Popup()">Help</button><br/>
</div>
</form>
Related
This is my index.html file. It has JavaScript but when JavaScript validation works >Submit button doesn't perform any action. But when I remove JavaScript code it submits the data to the database.
I need to understand where my code has faults or mistakes and why this is happening. How to validate that the arrival date should be smaller than the departure date.
<!DOCTYPE html>
<head>
<title>Book Accomodations</title>
<link rel="stylesheet" href="style.css">
<script>
function validate(){
var x =document.forms["myform"]["fname"].value;
var y =document.forms["myform"]["lname"].value;
var email =document.forms["myform"]["email"].value;
var filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var getSelectedValue = document.querySelector( 'input[name="payment"]:checked');
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert(" Last Name must be filled out");
return false;
}
else if (!email.match(filter)) {
alert(" Enter Proper Email ID");
return false;
}
else if(document.getElementById("country").value == "")
{
alert("Please select a country");
return false;
} else if(getSelectedValue == null) {
alert("Select Payment Mode")
return false;
}
return false;
}
</script>
</head>
<body>
<div class="form">
<form name ="myform" action="function.php" onsubmit="return validate();" id="form" method="POST" >
<label for="fname">First Name:</label>
<input type="text" id="fname" name="fname" /><br>
<label for="lname">Last Name:</label>
<input type="text" id="lname" name="lname" /><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" /><br>
<label for="arrival">Arrival Date:</label>
<input type="date" id="arrival " name="adate" ><br>
<label for="departure">Departure Date:</label>
<input type="date" id="departure " name="ddate" />
<br>
<label for="country">Choose a Country:</label>
<select id="country" name="country" form="myform" >
<option disabled selected value> -- select an option -- </option>
<option value="India">India</option>
<option value="U.S.A.">U.S.A.</option>
<option value="Nepal">Nepal</option>
<option value="Bangladesh">Bangladesh</option>
<option value="Germany">Germany</option>
<option value="Spain">Spain</option>
<option value="Italy">Italy</option>
<option value="Sri Lanka">Sri Lanka</option>
<option value="China">China</option>
</select>
<p>Payment Mode:</p>
<input type="radio" id="deb"
name="payment" value="Debit" />
<label for="deb">Debit Card</label>
<input type="radio" id="cred"
name="payment" value="Credit"/>
<label for="Credit">Credit Card</label>
<br>
<input type="submit" id="submit" name="submit" value="submit" style="width: 100px;"/>
<input type="reset" value="Reset" style="width: 100px; "/>
</form> </div>
</body>
You should return true at the end of your validate() function if your validation was successful. Right now you always return false. Thats why the button doesn´t seams to work.
Seems like you missed something.
You should return true after succesfull validation.
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert("Last Name must be filled out");
return false;
} else if (!email.match(filter)) {
alert("Enter Proper Email ID");
return false;
} else if (document.getElementById("country").value == "") {
alert("Please select a country");
return false;
} else if (getSelectedValue == null) {
alert("Select Payment Mode")
return false;
} else {
return true;
}
Or just return true after if-else statement.
I'm trying to get my HTML & Javascript code to generate a similar prompt (see image below something similar in principle). Instead of the prompt working a page called "HTML - Form Data Extraction Test" comes up instead.
Struggling to pin point where I'd gone wrong as my labels and ID's are in place, I've been using "getelementbyid", defined all the instances of when the messages should appear.
Any help would be greatly appreciated. Thanks in advance.
/* function validate()will validate form data */
function validate() {
var jref = document.getElementById("jref").value;
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var dob = document.getElementById("dob").value;
var email = document.getElementById("email").value;
var genm = document.getElementById("genm").checked;
var genf = document.getElementById("genf").checked;
var saddress = document.getElementById("saddress").value;
var stown = document.getElementById("stown").value;
var pnumber = document.getElementById("pnumber").value;
//NEED LABELS FOR
//state dropdown
//Skills drop down
var errMsg = "";
var result = true; /* assumes no errors */
//var pattern = /^[a-zA-Z ]+$/; /* regular expression for letters and spaces only */
if (jref == "") {
errMsg += "Job Reference Number cannot be Empty\n";
//errMsg = errMsg + "First Name cannot be
}
if (fname == "") {
errMsg += "First Name cannot be Empty\n";
}
if (lname == "") {
errMsg += "Last Name cannot be Empty\n";
}
if (dob == "") {
errMsg += "Date of Birth cannot be Empty\n";
}
if (email == "") {
errMsg += "Email cannot be Empty\n";
}
if ((genm == "") && (genf == "")) { //check whether gender is selected
errMsg += "A gender must be selected.\n";
}
if (saddress == "") {
errMsg += "Street Address cannot be Empty\n";
}
if (stown == "") {
errMsg += "Suburb or Town cannot be Empty\n";
}
if (pnumber == "") {
errMsg += "Phone Number cannot be Empty\n";
}
if (errMsg != "") {
alert(errMsg);
result = false;
}
return result;
}
function init() {
/* assign the <form> element to variable regForm */
var appForm = document.getElementById("appForm");
/* link function validate() to the onsubmit event of the form */
appForm.onsubmit = validate;
}
/* execute function init() once the window is loaded*/
window.onload = init;
<main>
<!-- Start of the form that the user fills out -->
<form method="post" action="http://mercury.swin.edu.au/it000000/formtest.php" id="appForm">
<h1>Job Application Form</h1>
<label for="jref">Job Reference Number</label><br>
<input type="text" name="jref" maxlength="5" id="jref" pattern="\d{4}" /><br>
<fieldset>
<label for="fname">First Name</label><br>
<input type="text" id="fname" maxlength="20" name="fname" /> <br>
<label for="lname">Last Name</label><br>
<input type="text" id="lname" maxlength="20" name="lname" /><br>
<label for="dob">Date of birth:</label><br>
<input id="dob" type="date" name="dob" /><br>
<label>Gender</label>
<input id="genm" type="radio" name="genm" value="Male" />
<label for="genm">Male</label>
<input id="genf" type="radio" name="genf" value="Female" />
<label for="genf">Female</label><br>
<label for="saddress">Street Address</label><br>
<input type="text" id="saddress" maxlength="40" name="saddress" /><br>
<label for="stown">Suburb/Town</label><br>
<input type="text" id="stown" maxlength="40" name="stown" /><br> State
<br>
<select name="slRank">
<option value="">Choose</option>
<option value="8">ACT</option>
<option value="8">ACT</option>
<option value="7">TAS</option>
<option value="6">SA</option>
<option value="5">WA</option>
<option value="4">NT</option>
<option value="3">QLD</option>
<option value="2">NSW</option>
<option value="1">VIC</option>
</select><br>
<label for="email">Email Address</label><br>
<input type="email" id="email" name="email" placeholder="example#gmail.com" /><br>
<label for="pnumber">Phone Number</label><br>
<input type="tel" id="pnumber" name="pnumber" placeholder="(##) ####-####" /><br> Skills
<select name="slRank">
<option value="">Choose</option>
<option value="9">Creativity</option>
<option value="8">Interpersonal Skills</option>
<option value="7">Critical Thinking</option>
<option value="6">Problem Solving</option>
<option value="5">Public Speaking</option>
<option value="4">Communication</option>
<option value="3">Collaboration</option>
<option value="2">Accounting</option>
<option value="1">Other</option>
</select><br /><br />
<label>Other Skills</label>
<br />
<textarea autofocus="autofocus" placeholder="Please fill out other skills you have here."></textarea><br>
<input type="submit" value="Apply" />
<input type="reset" value="Reset" />
</fieldset>
</form>
</main>
user this https://jqueryvalidation.org/ js library for form validation
i am creating a website using django, i have added a little js for validation, but it's not working. whenever i run the code it says
TypeError: document.getElementById(...) is null
html snippet
<form onsubmit=" return validate_bus()" action="confirm_bus/{{busname}}" method="post">
{% csrf_token %}
<div id="left">
<label>Departure date</label>
<input type="date" autocomplete="off" name="date" id="departuredate"> <br><br>
<label>Username</label>
<input type="text" name="username" id="BusUsername" autocomplete="off">
</div>
<div id="right">
<label>Number of seats</label><br>
<select autocomplete="off" name="seats" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<br>
</select><br><br>
<label> password</label>
<input type="password" autocomplete="off" name="password" id="password">
</div>
<label id="error_message">{{error_message}}</label><br>
<button type="submit">Confirm booking</button>
</form>
and this is my js snippet
function validate_bus()
{
var date = document.getElementById("departuredate").value;
var username = document.getElementById("BusUsername").value;
var seats = document.getElementById("seats").value;
var password = document.getElementById("password").value;
var date_regx = /^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$/
var username_regx = /^[a-zA-Z0-9_$.#]+$/
var password_regx = /^(?=.*\d).{4,12}$/
var seats_regx = /[1-6]{1}/
var valid = true
console.log(date, username, seats, password);
if (! date_regx.test(date))
{
valid = false;
}
if (! username_regx.test(username))
{
valid = false;
}
if (! seats_regx.test(seats))
{
valid = false;
}
if(! password_regx.test(password))
{
valid = false;
}
if (!valid)
{
var error = document.getElementById("error_message").innerHTML = "invalid input";
}
console.log(valid)
return valid;
};
Hi there in your var seats = document.getElementById("seats").value; calls an id that's doesn't exist.
Just add the id to your select element and it should fix your error.
ex:
<select autocomplete="off" id="seats" name="seats" >
I have a form that keeps resetting every time I hit the required field when I click submit. Is there a way for my form to not submit or clear up when I hit the submit button, while checking for the required fields? My form alerts me, the submits. I don't know how to stop that, and make the alert go from one text type to the next. Like it checks the first input type, if it meets the requirements, then it checks for the next input type, is that possible?
<html>
<!--All my images were taken from google images-->
<!--4/29/2016-->
<title>LMC GYM</title>
</body>
<link rel= " stylesheet " type="text/css" href="Acss.css" />
<head>
<script>
function validate_form (){
valid = true;
var emailverify = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var letter = /^[a-zA-Z]+$/;
var zip = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
if (emailverify.test(document.contact_form.contact_email.value) == false){
alert ("Please put in a valid email provider.");
valid = false;
}
if (document.contact_form.contact_email.value ==""){
alert ("Please put in your email.");
valid = false;
}
if (document.contact_form.contact_pass.value ==""){
alert ("Please put in a password.");
valid = false;
}
if (document.contact_form.contact_pass1.value != document.contact_form.contact_pass.value){
alert ("Please make sure passwords are the same.");
valid = false;
}
if (document.contact_form.contact_first.value ==""){
alert ("Please put in your first name.");
valid = false;
}
if (letter.test(document.contact_form.contact_first.value) == false){
alert ("No numbers! Please enter a valid first name.");
valid = false;
}
if (document.contact_form.contact_last.value ==""){
alert ("Please put in your last name.");
valid = false;
}
if (letter.test(document.contact_form.contact_last.value) == false){
alert ("No numbers! Please enter a valid last name.");
valid = false;
}
if (document.contact_form.contact_state.value ==""){
alert ("Please enter state abbrevation, example New York-NY.");
valid = false;
}
if (letter.test(document.contact_form.contact_state.value) == false){
alert ("Reminder no numbers! Please put in state abbrevation.");
valid = false;
}
if (document.contact_form.contact_city.value ==""){
alert ("Please put in your current city.");
valid = false;
}
if (letter.test(document.contact_form.contact_city.value) == false){
alert ("Reminder no numbers! Please put in your current city.");
valid = false;
}
if (document.contact_form.contact_add.value ==""){
alert ("Please put in your address.");
valid = false;
}
if (document.contact_form.contact_zip.value ==""){
alert ("Please put in your zip code.");
valid = false;
}
if (zip.test(document.contact_form.contact_zip.value) == false){
alert ("No letters in zip code!!.");
valid = false;
}
if (document.contact_form.contact_phone.value ==""){
alert ("Please put in your phone number.");
valid = false;
}
if (( document.contact_form.gen[0].checked == false) && (
document.contact_form.gen[1].checked == false )){
alert ("Please choose your Gender: Male or Female");
valid = false;
}
if (document.contact_form.Membership.selectedIndex == 0){
alert ("Please choose a membership.");
valid = false;
}
if (( document.contact_form.card[0].checked == false) && (document.contact_form.card[1].checked == false ) && (document.contact_form.card[2].checked == false ) && (document.contact_form.card[3].checked == false )){
alert ("Please choose a card type");
valid = false;
}
if (document.contact_form.contact_cn.value ==""){
alert ("Please put in your card number.");
valid = false;
}
if (document.contact_form.contact_cvv.value ==""){
alert ("Please put in your 3 digit cvv.");
valid = false;
}
if (document.contact_form.Expmonth.selectedIndex == 0){
alert ("Please choose a month on your credit card.");
valid = false;
}
if (document.contact_form.Expyear.selectedIndex == 0){
alert ("Please choose a year on your credit card.");
valid = false;
}
if (document.contact_form.contact_date.value ==""){
alert ("Please fill in the 'Expiration Date' box in the month and year format MMYY.");
valid = false;
}
if (document.contact_form.terms.checked == false){
alert ("Please check the Terms & Conditions box.");
valid = false;
}
return false;
}
</script>
</head>
<body>
<div class= "contains">
<div class ="head">
<h4> LMC GYM </h4>
<body background="https://wallpaperscraft.com/image/dumbbells_sports_gym_106546_3840x2 160.jpg">
</h4>
</div>
<div class ="nav">
<h5>Navigate</h5>
<ul>
<li>Home</li>
</br>
<li>Offers</li>
</br>
<li>Gym Form</li>
</ul>
</div><!--nav><-->
<div class="chunk">
</script>
</head>
<form name="contact_form" method="post" onSubmit="return validate_form ( );">
<h1> Signup now to join the LMC GYM </h1>
<fieldset>
<legend>Account Information:</legend>
E-mail: <input type="email" name="contact_email"> </br></br>
Password: <input type="password" name="contact_pass"></br></br>
Verify Password: <input type="password" name="contact_pass1"></br></br>
</fieldset>
</br>
<fieldset>
<legend>Contact Information:</legend>
First Name: <input type="text" name="contact_first" maxlength="13"> </br></br>
Last Name: <input type="text" name="contact_last" maxlength="13"> </br></br>
State: <input type="text" name="contact_state" maxlength="2"> </br></br>
City: <input type="text" name="contact_city" maxlength="13"> </br></br>
Address: <input type="text" name="contact_add" maxlength="21"> </br></br>
Zip Code: <input type="number" name="contact_zip" maxlength="5" > </br></br>
Phone Number: <input type="number" name="contact_phone" maxlength="10" > </br> </br>
Your Gender: <input type="radio" name="gen" value="Male"> Male
<input type="radio"name="gen" value="Female"> Female </br></br>
</fieldset> </br>
<fieldset>
<legend>Payment Information:</legend>
Membership:
<select name="Membership" >
<option value="">Please choose an option:</option>
<option value= "Bronze "> Bronze </option>
<option value= "Silver"> Silver </option>
<option value= "Gold">Gold</option> </select> </br></br>
Card Type: <input type="radio" name="card" value="Mastercard"> Mastercard
<input type="radio"name="card" value="Visa"> Visa </br>
<input type="radio"name="card" value="American Express"> American Express
<input type="radio"name="card" value="Discover"> Discover </br> </br>
Card Number: <input type="number" name="contact_cn" maxlength="16"> </br></br>
Card CVV: <input type="number" name="contact_cvv" min="009" maxlength="3"> </br></br>
Good Through:
<select name="Expmonth" >
<option value=""> Month:</option>
<option value= "01 "> 01 </option>
<option value= "02 "> 02 </option>
<option value= "03"> 03 </option>
<option value= "04">04</option>
<option value= "05 "> 05 </option>
<option value= "06"> 06 </option>
<option value= "07">07</option>
<option value= "08"> 08 </option>
<option value= "09">09</option>
<option value= "10"> 10 </option>
<option value= "11"> 11 </option>
<option value= "12">12</option> </select>
<select name="Expyear" >
<option value=""> Year:</option>
<option value= "18 "> 18 </option>
<option value= "19 "> 19 </option>
<option value= "20"> 20 </option>
<option value= "21">21</option>
<option value= "22 "> 22 </option>
<option value= "23"> 23 </option>
<option value= "24">24</option>
<option value= "25"> 25 </option>
<option value= "26">26</option>
<option value= "27"> 27 </option>
<option value= "28"> 28 </option>
<option value= "29">29</option> </select> </br></br>
</fieldset>
Do you agree to the Terms and Conditions?</br></br>
<input type="checkbox" name="terms" value="Yes"> Yes
</br></br>
<p><input type="submit" name="send" value="Submit"></p>
<p><input type="reset" name="reset"></p>
</form>
</body>
</html>
</div><!--"chunk"><-->
<div class="foot">
</div><!--foot><-->
</div><!--contains><-->
</body>
</html>
event.preventDefault(); prevents default behaviour (duh), which doesn't refresh the page.
I would use the following piece of code:
function validate_form(){
//
//
//
}
var form = document.querySelector('form');
form.addEventListener('submit', function(event){
event.preventDefault();
validate_form();
}
But, as RobG suggested, this would prevent the default submission routine as well. So you should explicitly add a call to submit function (or the form's submit method, if you are using it), e.g.
event.preventDefault();
if(validate_form()){
form.submit()
} else { /*error handling routine*/ }
Or you could do it in one line like this (doesn't make sense with default submit, since it would be implementing the default behaviour anyway):
event.preventDefault();
return validate_form() && my_submit_nethod();
// form submits only if validate_form evaluated to true
Or, just return the validation result and leave the form to submit. Note, that currently, if the validation returns true, your page will refresh.
return validate_form();
Finally, another thing you could do is change the form's submission method:
var form = document.querySelector('form');
function my_submit_routine(){
// here goes your code for submitting
};
form.submit = my_submit_routine;
I have simple form with fields for First and Last name and a salutation. I have a javascript function that should validate if the fields or empty or exceed 25 characters. The function mostly works except on .focus(); the page just reloads. Not sure what I'm doing wrong, please advise. Thanks in advance.
function validate(){
//alert ("TEST!!!");
var first = document.getElementById('firstname').value;
if (first.length == 0 || first.length > 25){
alert ("Please enter your first name, no longer than 25 chracters.");
document.getElementById('firstname').focus();
return false;
}
var last = document.getElementById('lastname').value;
if (last.length == 0 || last.length > 25){
alert ("Please enter your last name, no longer than 25 characters.");
document.getElementsByName('lastname').focus();
return false;
}
var title = document.getElementById('title').value;
if (document.getElementById('title').selectedIndex == 0){
alert ("Please select your salutation");
document.getElementById('title').focus();
return false;
}
return true;
}
In the html the form is:
<form name="name" form id="name" method="post" onsubmit="validate();">
Salutation: <select name="title" select id="title">
<option selected="Please Select">Please select</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss">Miss</option>
</select><br><br>
First Name : <input type="text" input id="firstname" name="firstname">
Last Name : <input type="text" input id="lastname" name="lastname"><br><br>
<input type="submit" value="Submit"><br><br>
</form>
Change:
onsubmit="validate();">
to:
onsubmit="return validate();">