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;
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 have a function to validate all fields, but I also want to disable the submit button until the fields are filled out AND validation is complete. What is the best way to go about doing this? I'm very new to JavaScript so very specific instructions/explanation is appreciated :)
function fieldValidation() {
var name = document.forms['RegForm']['Name'].value;
var address = document.forms['RegForm']['Address'].value;
var email = document.forms['RegForm']['EMail'].value;
var password = document.forms['RegForm']['Password'].value;
var telephone = document.forms['RegForm']['Telephone'].value;
var job = document.forms['RegForm']['Job'].value;
var comment = document.forms['RegForm']['Comment'].value;
var fullName = /^[a-zA-Z]+ [a-zA-Z]+$/;
var phnFormat = /((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}/;
if (name === '') {
alert('Please enter your name.');
return false;
}
if (!fullName.test(name)) {
alert('Please make sure we have your full name.');
return false;
}
if (address === '') {
alert('Please enter your address.');
return false;
}
if (email === '') {
alert('Please enter your e-mail address.');
return false;
}
if (password === '') {
alert('Please enter a password.');
return false;
}
if (telephone === '') {
alert('Please enter your telephone number.');
return false;
}
if (!phnFormat.test(telephone)) {
alert('Please enter your phone number in the following format: (123) 555-1212)');
return false;
}
if (job.value === '') {
alert('Please select a job choice.');
return false;
}
if (comment.value === '') {
alert('Please enter a comment.');
return false;
}
return true;
}
<div class="container">
<main>
<form name="RegForm" action="/submit.php" onsubmit="return fieldValidation()" method="post">
<p>Name: <input type="text" size=65 name="Name" id="nameInput"> </p><br>
<p>Address: <input type="text" size=65 name="Address"> </p><br>
<p>E-mail Address: <input type="email" size=65 name="EMail"> </p>
<input type="checkbox" id="confirmApp" name="confirm">
<label for="confirmApp">I want to receive an email confirming my application.</label>
<br>
<p>Password: <input type="password" size=65 name="Password"> </p><br>
<p>Telephone: <input type="tel" size=65 name="Telephone"> </p><br>
<label for="jobChoice">Job Choice:</label>
<select name="Job" id="jobChoice">
<option value="">--- Select Job Choice ---</option>
<option value="IT">IT</option>
<option value="Human Resources">Human Resources</option>
<option value="Maintenance">Maintenance</option>
<option value="Management">Management</option>
<option value="Other">Other</option>
</select></p><br><br>
<p>Comments: <textarea cols="100" rows="10" name="Comment"> </textarea></p>
<p><input type="submit" value="send" name="Submit" id="submitBtn">
<input type="reset" value="Reset" name="Reset"></p>
</form>
</main>
</div>
You could do it in a couple of ways:
You could have a onclick="your validation function" for each input running your validation code.
Or you could add the required tag to each required input, this way the user cant submit the form unless every required field is filled in a.e. <input type="text" size="65" name="Name" id="nameInput"required>, however option two does not hide the submit button.
If you only want to disable the submission and not the submit button persé I'd suggest using the required tag for the relevant input fields.
I am trying to validate my form before submitting it but the form is being submitted anyway without any alerts coming up, even though the form is being submitted blank. When the submit button is clicked I want to make sure information has been completed and is correct, and when it is blank or incorrect an alert should come up without submitting the form.
Thanks
HTML
<!DOCTYPE html>
<html>
<head>
<title>Oaktown Football Club</title>
<meta charset="UTF-8">
<script src="formValidation.js"></script>
</head>
<body>
<header>
<img src="logo.png" alt="Oaktown Football Club Logo"/>
<h1>Oaktown Football Club</h1>
<nav>
Homepage
Competitions
Contact
</nav>
</header>
<section>
<h2>Contact Us</h2>
<article>
<h3>Secretary</h3>
<p>Name: Laci Tanner</p>
<p>Phone: (02) 6620 3324</p>
<p>Email: secretary#oaktownfa.com.au</p>
<h3>Leave us a message</h3>
<form method="post" action="actionPage.html" name="contactForm" onsubmit="return formValidation();">
<label>Full Name:</label><br>
<input type="text" size="35" name="fullName" id="name"><br>
<br><label>Email:</label><br>
<input type="text" size="35" name="email" id="email"><br>
<br><label>Phone:</label><br>
<input type="text" size="35" name="phone" id="phone"><br>
<br><label>Team:</label><br>
<select name="team"><br>
<option>Please Choose</option>
<option>Adults</option>
<option>Under 12s</option>
<option>Under 6s</option>
</select><br>
<br><label>I am:</label><br>
<select name="Member"><br>
<option>Please Choose</option>
<option>Thinking about joining the club</option>
<option>Already a club member</option>
</select><br>
<br><label>Comments:</label><br>
<textarea id="comments" type="text" rows="5" cols="75"></textarea><br>
<br><input id="submit" type="submit" value="Submit"><br>
<br><input type="reset">
</form>
</article>
</section>
<footer>
<p>Copyright - Oaktown Football Club</p>
</footer>
</body>
</html>
JavaScript
function formValidation()
{
var name = document.contactForm.fullName;
var email = document.contactForm.email;
var phone = document.contactForm.phone;
var comment = document.contactForm.comment;
if (fullName.value == "") {
alert("Please enter your name!");
fullName.focus();
return false;
}
if (email.value == "") {
alert("Please enter your email address!");
email.focus();
return false;
}
if (email.value.indexOf("#", 0) < 0) {
alert("Please enter a valid email address!");
email.focus();
return false;
}
if (email.value.indexOf(".", 0) < 0) {
alert("Please enter a valid email address!");
email.focus();
return false;
}
if (phone.value == "") {
alert("Please enter your phone number!");
phone.focus();
return false;
}
if (phone.length < 2) {
alert("Please enter a valid phone number!");
phone.focus();
return false;
}
if (comments.value == "") {
alert("Please leave us a comment!");
comments.focus();
return false;
}
{
return true;
}
}
It seems you had stored the value of the 'Full Name' in the variable 'name', but you were checking in your first 'if' block, you were checking if "fullName.value == ''".
Thus, a 'Reference Error' was being thrown.
After correcting it to if "name.value == ''", the code works fine.
Please find below the working code in JSBin :-
http://jsbin.com/kemokijucu/edit?html,js,console,output
You get name :
var name = document.contactForm.fullName;
But check by fullName :
if (fullName.value == "") {
alert("Please enter your name!");
fullName.focus();
return false;
}
Please up the code :)
You have made mistake in fetching & using name element from the form. Below is the correction in JS.
function formValidation() {
var fullName = document.contactForm.name;
var email = document.contactForm.email;
var phone = document.contactForm.phone;
var comment = document.contactForm.comment;
if (fullName.value == "") {
alert("Please enter your name!");
fullName.focus();
return false;
}
if (email.value == "") {
alert("Please enter your email address!");
email.focus();
return false;
}
if (email.value.indexOf("#", 0) < 0) {
alert("Please enter a valid email address!");
email.focus();
return false;
}
if (email.value.indexOf(".", 0) < 0) {
alert("Please enter a valid email address!");
email.focus();
return false;
}
if (phone.value == "") {
alert("Please enter your phone number!");
phone.focus();
return false;
}
if (phone.length < 2) {
alert("Please enter a valid phone number!");
phone.focus();
return false;
}
if (comments.value == "") {
alert("Please leave us a comment!");
comments.focus();
return false;
} {
return true;
}
}
<title>
Oaktown Football Club</title>
<body>
<header>
<img src="logo.png" alt="Oaktown Football Club Logo" />
<h1>Oaktown Football Club</h1>
<nav>
Homepage
Competitions
Contact
</nav>
</header>
<section>
<h2>Contact Us</h2>
<article>
<h3>Secretary</h3>
<p>Name: Laci Tanner</p>
<p>Phone: (02) 6620 3324</p>
<p>Email: secretary#oaktownfa.com.au</p>
<h3>Leave us a message</h3>
<form method="post" action="actionPage.html" name="contactForm" onsubmit="return formValidation();">
<label>Full Name:</label>
<br>
<input type="text" size="35" name="fullName" id="name">
<br>
<br>
<label>Email:</label>
<br>
<input type="text" size="35" name="email" id="email">
<br>
<br>
<label>Phone:</label>
<br>
<input type="text" size="35" name="phone" id="phone">
<br>
<br>
<label>Team:</label>
<br>
<select name="team">
<br>
<option>Please Choose</option>
<option>Adults</option>
<option>Under 12s</option>
<option>Under 6s</option>
</select>
<br>
<br>
<label>I am:</label>
<br>
<select name="Member">
<br>
<option>Please Choose</option>
<option>Thinking about joining the club</option>
<option>Already a club member</option>
</select>
<br>
<br>
<label>Comments:</label>
<br>
<textarea id="comments" type="text" rows="5" cols="75"></textarea>
<br>
<br>
<input id="submit" type="submit" value="Submit">
<br>
<br>
<input type="reset">
</form>
</article>
</section>
<footer>
<p>Copyright - Oaktown Football Club</p>
</footer>
</body>
Do try and debug the same using console in the browser.
You can change the type attribute of email field to email for auto email validation on the field.
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>
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();">