Validating a form using Javascript - javascript

I'm having problems trying to validate an entire form using Javascript.
"Add JavaScript code to produce an error message and suppress submission of the form if any quantity field contains non-numeric data. (It's OK for a quantity to be empty, but if it's non-empty, it must have only numbers.) Add an action= attribute to your tag to submit the form to a website (not going to put actual website). Test that the form is submitted correctly when the quantities are numeric or empty, and that an error message is produced otherwise."
I've done all the instructions asked me to do and it isn't working. We are supposed to use the form that we created in one of the previous labs. Here is the code that I have been working on.
<!DOCTYPE html>
<html>
<head>
<title>Lab 6, Part 3</title>
<meta charset="UTF-8"/>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
<script type="text/javascript">
function validateForm(){
var a = document.forms["myform"]["Pokemon"].value;
var b = document.forms["myform"]["Pokeball"].value;
var c = document.forms["myform"]["Pikachu"].value;
var d = document.forms["myform"]["firstname"].value;
var e = document.forms["myform"]["lastname"].value;
var f = document.forms["myform"]["streetaddress"].value;
var g = document.forms["myform"]["city"].value;
var h = document.forms["myform"]["zipcode"].value;
if (a = null || a == ""){
alert("Grapes must be filled out!");
return false;
}
if (b = null || b == ""){
alert("Cherries must be filled out!");
return false;
}
if (c = null || c == ""){
alert("Strawberries must be filled out!");
return false;
}
if (d = null || d == ""){
alert("First Name must be filled out!");
return false;
}
if (e = null || e == ""){
alert("Last Name must be filled out!");
return false;
}
if (f = null || f == ""){
alert("Street Address must be filled out!");
return false;
}
if (g = null || g == ""){
alert("City must be filled out!");
return false;
}
if (h = null || h == ""){
alert("Zip Code must be filled out!");
return false;
}
}
</script>
</head>
<body><form>
<form name="myform" action="http://weblab.kennesaw.edu/formtest.php"
onsubmit="return validateForm()"
method = "post">
<h1 style="text-align:center">Lab 6, Part 3</h1>
<h2 style="text-align:center">IT 3203</h2>
<p style="text-align:center">Main Page!</p>
<p>Grapes</p><input type=text size=3 maxlength=3 name="Pokemon">
<p>Cherries</p><input type=text size=3 maxlength=3 name="Pokeball">
<p>Strawberries</p><input type=text size=3 maxlength=3 name="Pikachu">
<br>
<label>First Name
<input type="text"
name="firstname" id="firstname"
size="25" />
</label>
<br>
<br>
<label>Last Name
<input type="text"
name="lastname" id="lastname"
size="25" />
</label>
<br>
<br>
<label>Street Address
<input type="text"
name="streetaddress" id="streetaddress"
size="35" />
</label>
<br>
<br>
<label>City
<input type="text"
name="city" id="city"
size="25" />
</label>
<label>State:
<select name="state">
<option>Please Select</option>
<option>Alabama</option>
<option>Alaska</option>
<option>Arizona</option>
<option>Arkansas</option>
<option>California</option>
<option>Colorado</option>
<option>Connecticut</option>
<option>Delaware</option>
<option>Florida</option>
<option>Georgia</option>
<option>Hawaii</option>
<option>Idaho</option>
<option>Illinois</option>
<option>Indiana</option>
<option>Iowa</option>
<option>Kansas</option>
<option>Kentucky</option>
<option>Louisiana</option>
<option>Maine</option>
<option>Maryland</option>
<option>Massachusetts</option>
<option>Michigan</option>
<option>Minnesota</option>
<option>Mississippi</option>
<option>Missouri</option>
<option>Montana</option>
<option>Nebraska</option>
<option>Nevada</option>
<option>New Hampshire</option>
<option>New Jersey</option>
<option>New Mexico</option>
<option>New York</option>
<option>North Carolina</option>
<option>North Dakota</option>
<option>Ohio</option>
<option>Oklahoma</option>
<option>Oregon</option>
<option>Pennsylvania</option>
<option>Rhode Island</option>
<option>South Carolina</option>
<option>South Dakota</option>
<option>Tennessee</option>
<option>Texas</option>
<option>Utah</option>
<option>Vermont</option>
<option>Virginia</option>
<option>Washington</option>
<option>West Virginia</option>
<option>Wisconsin</option>
<option>Wyoming</option>
</select>
</label>
<br>
<br>
<label>Zip code:
<input type="text"
name="zipcode" id="zipcode"
size="20" />
</label>
</form>
<br>
<br>
<label>Visa
<input type="radio" name="pref_payment"
id="pref_payment_visa" value="visa" checked />
</label><br />
<label>MasterCard
<input type="radio" name="pref_payment"
id="pref_payment_master" value="master" checked />
</label><br />
<label>American Express
<input type="radio" name="pref_payment"
id="pref_payment_american" value="american" checked />
</label><br />
<input type="button" onclick="confirmation()" value="submit">
</form>
</body>
</html>
It is probably something minor that I have overlooked or something. Oh and we had to save the files in .php so maybe that has a lot to do with it.

1) Check your form tag. You got two there.
<form>
2) Your submit button type.
Should be:
type="submit"
Not:
type="button"
And no need to add:
onclick="confirmation()"
http://plnkr.co/edit/Ml2KWgfU5KG5gmBpf8Fe?p=preview

Related

Javascript Validate Input fields + Select Field

I am using a very easy (but functional for my needs) Javascript script to validate input fields.
Here my main code:
<script language = "javascript">
function manage(txt) {
var bt = document.getElementById('send');
if (txt.value && txt2.value && txt3.value != '') {
bt.disabled = false;
}
else {
bt.disabled = true;
}
}
</script>
Here are my fields
<input type="text" name="FNAME" id="txt" class="input" size="20" placeholder="First Name *" onkeyup="manage(this)">
<input type="text" name="LNAME" id="txt2" class="input" size="20" placeholder="Last Name *" onkeyup="manage(this)">
<input type="text" name="EMAIL" id="txt3" class="input" size="20" placeholder="Email *" onkeyup="manage(this)">
and here my Submit button:
<input type="submit" name="submit" id="send" class="button button-primary" value="Subscribe" disabled>
What this does is to leave the submit button disabled until all fields have some value entered and works absolutely fine, however I also have a new and additional select option being:
<select name="Countries">
<option value="">Select Country</option>
<option value="Afghanistan">Afghanistan</option>
<option value="Åland Islands">Åland Islands</option>
<option value="Albania">Albania</option>
......
</select>
I've tried to apply the following changes:
<script language = "javascript">
function manage(txt) {
var bt = document.getElementById('send');
if (txt.value && txt2.value && txt3.value && txt4.value != '') {
bt.disabled = false;
}
else {
bt.disabled = true;
}
}
</script>
<select name="Countries" id="txt4" onkeyup="manage(this)">
<option value="">Select Country</option>
<option value="Afghanistan">Afghanistan</option>
<option value="Åland Islands">Åland Islands</option>
<option value="Albania">Albania</option>
......
</select>
However it does not seem to work. Some expert advise would be greatly appreciated. Thank you very much.
The proper form is
if (txt.value!='' && txt2.value!='' && txt3.value!='' && txt4.value!='')
You don't want to set the onkyeup event, but onchange. More universal event is oninput.
You should also check the required form elements tag attribute, which can provide you similar functionality without javascript. See here.
First of all, listening keyup event on your select will work only in case if select was changed by the keyboard. In case if it was changed by mouse, your event won't be fired. Better to listen onchange
On another hand, you should check the emptiness of all text fields, as you do for txt4.value!='':
if (txt.value!='' && txt2.value!='' && txt3.value!='' && txt4.value!='') {
...
}
Now it will work.
function manage(txt) {
var bt = document.getElementById('send');
if ( txt.value != '' && txt2.value != '' && txt3.value != '' && txt4.value != '' ) {
bt.disabled = false;
}
else {
bt.disabled = true;
}
}
<input type="text" name="FNAME" id="txt" class="input" size="20" placeholder="First Name *" onkeyup="manage(this)">
<input type="text" name="LNAME" id="txt2" class="input" size="20" placeholder="Last Name *" onkeyup="manage(this)">
<input type="text" name="EMAIL" id="txt3" class="input" size="20" placeholder="Email *" onkeyup="manage(this)">
<select name="Countries" id="txt4" onchange="manage(this)">
<option value="">Select Country</option>
<option value="Afghanistan">Afghanistan</option>
<option value="Åland Islands">Åland Islands</option>
<option value="Albania">Albania</option>
</select>
<input type="submit" name="submit" id="send" class="button button-primary" value="Subscribe" disabled>
I have done this type of functionality before. So I'm sharing my code here.
HTML Code
<form method="Post" class="form">
<input type="text" name="FNAME" id="txt" class="input" size="20" placeholder="First Name *" onblur="manage(this)">
<input type="text" name="LNAME" id="txt2" class="input" size="20" placeholder="Last Name *" onblur="manage(this)">
<input type="text" name="EMAIL" id="txt3" class="input" size="20" placeholder="Email *" onblur="manage(this)">
<select name="Countries" id="txt4" onchange="manage(this)" class="input">
<option value="">Select Country</option>
<option value="Afghanistan">Afghanistan</option>
<option value="Åland Islands">Åland Islands</option>
<option value="Albania">Albania</option>
</select>
<input type="submit" name="submit" id="send" class="button button-primary" value="Subscribe" disabled>
</form>
Javascript Code:
<script>
function manage($e){
var input = document.getElementsByClassName("input");
var status=false;
for(var i=0;i<input.length;i++){
if(input[i].value.trim()!='' && input[i].value.trim()!=null && input[i].value.trim()!=undefined){
status = true;
} else {
status = false;
break;
}
}
console.log(status);
if(status===true){
var email = document.getElementById("txt3").value;
if(!(/^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.trim()))){console.log('1');
document.getElementById('send').disabled = true;
} else {console.log('2');
document.getElementById('send').disabled = false;
}
} else {
document.getElementById('send').disabled = true;
}
}
</script>
There are many ways to resolve this type of functionality but for this case, I have used the above code to achieve the goal. If you have any queries, please let me know. Thanks.

Why doesn't Javascript validate my html code?

This is my first attempt at working with javascript and forms; for some reason my html website elements aren't being validated and I am not sure why. My goal with this form is trying to validate the elements that have an '*' next to them. For some reason the only element that is being validated is email and nothing else. Name, dates, the checkbox aren't. I have been trying to find a fix, but nothing seems to work.
<!doctype html>
<html>
<head>
<link href="styles.css" rel="stylesheet">
<script src="script.js"></script>
<meta charset="utf-8">
<title>Form</title>
</head>
<body>
<div class="container">
<h1>Travel Reservation Form</h1>
<h4>* denotes mandotory field</h4>
<form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post">
<fieldset>
<legend>Personal Details</legend>
<label class="align">Full name:<span>*</span></label> <input type="text" name="fullname" placeholder="James Bond">
<br><br>
<label class="align">Email<span>*</span></label>
<input type="email" name="mail" placeholder="james#gmail.com">
<br><br>
<label class="align">Date of Birth<span>*</span></label> <input type="date" name="DOB" placeholder="dd/mm/yy">
</fieldset>
<br>
<label>Select Tour Package<span>*</span>:</label>
<select name="package">
<option value="1">Tokyo</option>
<option value="2">Shanghai</option>
<option value="3">Bangkok</option>
<option value="4">Jakarta</option>
<option value="5">Mumbai</option>
</select>
<label>Number of persons<span>*</span>:</label>
<select name="party">
<option value="1">One Adult</option>
<option value="2">Two Adults</option>
<option value="3">Three Adults</option>
<option value="4">Four Adults</option>
<option value="5">Five Adults</option>
</select>
<br><br>
<label>Arrival Date<span>*</span>:</label> <input type="date" name="arrival" placeholder="dd/mm/yy">
<br><br>
<p>What Intrests you the most?<span>*</span>:</p>
<input class="alignp" type="checkbox" name="interest" value="shopping"> Shopping <br><br>
<input class="alignp" type="checkbox" name="interest" value="dining"> Dining <br><br>
<input class="alignp" type="checkbox" name="interest" value="dancing"> Dancing <br><br>
<input class="alignp" type="checkbox" name="interest" value="SightS"> Sightseeing <br><br><br>
<label>Discount Coupon code:</label> <input type="text" name="dis_code" value=""><br><br>
<label>Terms and Conditions<span>*</span><input type="radio" name="tos" value="yes" checked>I agree</label>
<input type="radio" name="tos" value="yes">I disagree
<p>Please provide any additional information below:- </p>
<textarea name="message" rows="5" cols="45" placeholder="Please type here...."></textarea><br><br>
<button class="btn-submit" type="submit" value="Submit">Submit</button>
<button class="btn-reset" type="reset" value="Reset">Reset</button>
</form>
</div>
</body>
</html>
Here is the javascript that is being linked in the html. I am unsure whether the issue is with my html code or with my javascript.
// JavaScript Document
function validateForm()
{
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var dob = document.forms["myForm"]["DOB"].value;
var packages = document.forms["myForm"]["package"].value;
var arrival = document.forms["myForm"]["arrival"].value;
//var interest = document.forms["form"]["interest"].value;
var ToS = document.forms["myForm"]["tos"].value;
var checkbox = document.querySelector('input[name="interest"]:checked');
var matches = name.match(/\d+/g);
if (matches != null) {
alert("Name has a number in it!");
}
if (name == "") {
alert("Name must be filled out");
return false;
}
if (email == "") {
alert("Email must be filled out");
return false;
}
if (dob == "") {
alert("Date of Birth must not be empty");
return false;
}
if (arrival == "") {
alert("Arrival Date must not be empty");
return false;
}
if(ToS == false) {
alert("You must agree to the Terms of Service");
return false;
}
if(validateEmail(email) == false){
alert("Must enter a valid email");
}
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if(dob != '' && !dob.match(re)) {
alert("Invalid date format");
return false;
}
if(arrival != '' && !arrival.match(re)) {
alert("Invalid arrival date format") ;
return false;
}
if(name.length >= 30){
alert("Name must be less than 30 characters!");
return false;
}
if(!checkbox){
alert("Please select an interest!");
return false;
}
}
function validateEmail(email)
{
return /\S+#\S+\.\S+/.test(email);
}
So I have no idea what your PHP form did, so I actually just pulled all the form code for now. There were a lot of little issues but honest mistakes. Example: you don't want a return statement after every validation if you want to continue validating the rest of the fields. I combined some separate validations into if/else's since they were validations on the same field. I used ID's to make my life easier and since I dumped the form code. Feel free to swap back to what you want. I also updated your regex since the date field returns YYYY/MM/DD. Since this doesn't post anywhere you can play with it for a while, before tying back into your php form. I also pulled the check for 30 characters and added a max field length to name. You could also set min and max date ranges for the date fields and a bunch of other things to help make the fields themselves more foolproof. There are also libraries that handle this kind of thing for you, you don't have to re-invent the wheel, but if you're just looking to play around with it this should get you started. Good Luck
<!doctype html>
<html>
<body>
<div class="container">
<h1>Travel Reservation Form</h1>
<h4>* denotes mandotory field</h4>
<fieldset>
<legend>Personal Details</legend>
<label class="align">Full name:<span>*</span></label> <input type="text" name="fullname" id='name' maxlength="30" placeholder="James Bond">
<br><br>
<label class="align">Email<span>*</span></label>
<input id="email" type="email" name="mail" placeholder="james#gmail.com">
<br><br>
<label class="align">Date of Birth<span>*</span></label> <input type="date" id="dob" name="DOB" placeholder="dd/mm/yy">
</fieldset>
<br>
<label>Select Tour Package<span>*</span>:</label>
<select id='package' name="package">
<option value="1">Tokyo</option>
<option value="2">Shanghai</option>
<option value="3">Bangkok</option>
<option value="4">Jakarta</option>
<option value="5">Mumbai</option>
</select>
<label>Number of persons<span>*</span>:</label>
<select name="party">
<option value="1">One Adult</option>
<option value="2">Two Adults</option>
<option value="3">Three Adults</option>
<option value="4">Four Adults</option>
<option value="5">Five Adults</option>
</select>
<br><br>
<label>Arrival Date<span>*</span>:</label> <input type="date" name="arrival" id="arrival" placeholder="dd/mm/yy">
<br><br>
<p>What Intrests you the most?<span>*</span>:</p>
<input class="alignp" type="checkbox" name="interest" value="shopping"> Shopping <br><br>
<input class="alignp" type="checkbox" name="interest" value="dining"> Dining <br><br>
<input class="alignp" type="checkbox" name="interest" value="dancing"> Dancing <br><br>
<input class="alignp" type="checkbox" name="interest" value="SightS"> Sightseeing <br><br><br>
<label>Discount Coupon code:</label> <input type="text" name="dis_code" value=""><br><br>
<label>Terms and Conditions<span>*</span>
<input type="radio" name="tos" id="accpeted" value="agree" checked>I agree</label>
<input type="radio" name="tos" id="unaccepted" value="disagree">I disagree
<p>Please provide any additional information below:- </p>
<textarea name="message" rows="5" cols="45" placeholder="Please type here...."></textarea><br><br>
<button class="btn-submit" id="submit" onclick="return validateForm()">Submit</button>
</div>
<script>
// JavaScript Document
function validateForm() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var dob = document.getElementById("dob").value;
//Select Box
var e = document.getElementById("package");
// Selected Item
var packages = e.options[e.selectedIndex].value;
var arrival = document.getElementById("arrival").value;
//var interest = document.getElementById("").value;
var tos = document.querySelector('input[name="tos"]:checked').value;
//var checkbox = document.getElementById("").value;;
var matches = name.match(/\d+/g);
var re = /^\d{4}([.\/-])\d{2}\1\d{2}$/;
if (!name) {
alert("Name must be filled out");
} else {
if (matches != null) {
alert("Name has a number in it!: " + name);
}
}
if (!email) {
alert("Email must be filled out");
} else {
if (validateEmail(email) == false) {
alert("Must enter a valid email: " + email);
}
}
if (!dob) {
alert("Date of Birth must not be empty");
} else {
if (!dob.match(re)) {
alert(" Dob has Invalid date format: " + dob);
}
}
if (!arrival) {
alert("Arrival Date must not be empty");
} else {
if (!arrival.match(re)) {
alert(" Dob has Invalid date format: " + arrival);
}
}
if (tos != "agree") {
alert("You must agree to the Terms of Service");
}
}
function validateEmail(email) {
return /\S+#\S+\.\S+/.test(email);
}
</script>
</body>
</html>

How do I add checks to make the code to display 'Password too short' and 'Height is not a number?'

I have to add checks to the checkSubmit() function so that it will give the following response
Passwords do not match
Passwords is too short(minimum 4 characters)
Height is not a number
I have managed the first one however I have no idea where to start with the other two. I'll post all the code just to be safe in case I missed something.
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Form Validation</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles/styles.css">
<link rel="stylesheet" type="text/css" href="styles/forms.css">
<script type="text/javascript">
window.onload=init;
var form;
function init() {
form = document.getElementById('testform');
form.addEventListener("submit", checkSubmit, false);
form.addEventListener("reset", checkReset, false);
form['colour'].addEventListener("change", checkSubmit, false);
form['name'].focus();
}
String.prototype.trim=function() {
return this.replace(/^\s+1\s+$/g, '');
}
function whichButton(name) {
var buttons=document.getElementsByName(name);
for (var i in buttons) {
if(buttons[i].checked) return buttons[i].value
}
return false;
}
function showOtherColour() {
document.getElementById('othercolour').style.visibility=
form['colour'].value=='other' ? 'visible' : 'hidden';
}
function checkSubmit() {
error = new Array();
//Fill the array with the error value
form['name'].value=form['name'].value.trim();
form['email'].value=form['email'].value.trim();
form['town'].value=form['town'].value.trim();
form['state'].value=form['state'].value.trim();
form['postcode'].value=form['postcode'].value.trim();
form['dob'].value=form['dob'].value.trim();
form['height'].value=form['height'].value.trim();
//Check required fields
if(!form['name'].value)
error.push('Missing Name');
if(!form['email'].value)
error.push('Missing Email Address');
if(!form['password'].value)
error.push('Missing Password');
//Check valid email address
var pattern=/^[a-zA-Z0-9._%-]+#[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4})$/;
if(!form['email'].value.match(pattern))
error.push('Invalid Email Address');
//Check State
//Check Post Code has 4 digits
var pattern=/^\d{4}$/;
if(!form['postcode'].value.match(pattern))
error.push('Invalid Post Code');
//Check password matches confirmation
//var password = ;
/*
if(!form['passwordConfirm'].value.match(password)){
error.push("Passwords don't match");
}*/
console.log(form['confirm'].value);
console.log(form['password'].value);
if(!form['confirm'].value.match(form['password'].value)){
error.push('Passwords do not match');
}
//Check that one Gender item is selected
if(whichButton('gender')===false)
error.push('Please choose a Gender');
//Check that "Other" field is filled
if (!form['colour'].value ||
(form['colour'].value=='other' && !form['othercolour'].value))
error.push('Colour is not selected');
if(error.length) { // if there are errors
alert(error.join("\n"))
return false;
}
else return true;
//return confirm("This will submit the form"); //Temporary placeholder
}
function checkReset() {
return confirm("This will clear the form data");
}
</script>
<style type="text/css">
body,td,th {
font-size: 0.9em;
}
</style>
</head>
<body>
<div id="body">
<h1>Form Validation</h1>
<form action="http://test.miform.net" method="post" id="testform">
<fieldset>
<label>Name<br><input type="text" name="name" class="wide"></label>
<label>Email Address<br><input type="text" name="email" class="wide"></label>
</fieldset>
<fieldset>
<label>Address<br><input type="text" name="street" class="wide"></label>
<label>Town<br><input type="text" name="town" class="narrow"></label>
<label>State<br><input type="text" name="state" class="narrow"></label>
<label>PostCode<br><input type="text" name="postcode" class="narrow"></label>
</fieldset>
<fieldset>
<label>Password<br><input type="password" name="password" class="medium"></label>
<label>Confirm Password<br><input type="password" name="confirm" class="medium"></label>
</fieldset>
<fieldset>
<label>Date of Birth<br><input type="text" name="dob" class="medium"></label>
<label>Height<br><input type="text" name="height" class="medium"></label>
</fieldset>
<fieldset>
<legend>Gender</legend>
<label><input type="radio" name="gender" value="f">Female</label>
<label><input type="radio" name="gender" value="m">Male</label>
</fieldset>
<fieldset>
<label>Colour
<select name="colour">
<option value="">Select...</option>
<option value="black">Black</option>
<option value="white">White</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="cyan">Cyan</option>
<option value="magenta">Magenta</option>
<option value="yellow">Yellow</option>
<option value="other">Other</option>
</select>
</label>
<input type="text" id="othercolour">
</fieldset>
<input type="reset" name="reset" value="Clear Form">
<input type="submit" name="send" value="Send Off">
</form>
</div>
</body>
</html>
Do this for the second:
if (form['password'].value.length < 4) {
error.push("Password is too short");
}
And this for the third:
if (isNan(Number(form['height'].value))) {
error.push("Height is not a number");
}

javascript popup window with switch statement

Create a button called “GO TO OTHER WEBSITES” on your form that will call a function to give a popup window to go to the user’s choice of url and window size.
The function will use a prompt box to give the user at least 3 choices of urls (other websites related to your website) to choose from.
Use a switch statement to set the chosen url and validate the user choice, do not continue until you have a valid choice.
The user will then be prompted to enter the height and width of the window in pixels. This must be validated for a minimum height and width of 500. Do not continue until you have a valid height and width.
Display the chosen url in a window using this resolution. (Hint: to set the additional properties of the window.open method you will need to create a string variable to set the width and height.)
Here is my HTML
<!DOCTYPE html>
<html>
<head>
<script src= "../javascript/a1.js"></script>
<title>HTML5 Template</title>
</head>
<body>
<h1>Sign Up form</h1>
<form name="userForm" onsubmit= "return validateForm()" >
First name: <input type="text" id="firstname" size="30" />
<br><br>
Last name: <input type="text" id="lastname" size="30" />
<br><br>
Postcode: <input type="text" id="postcode" size="30" />
<br><br>
Email: <input type="text" id="email" size="30" />
<br><br>
<h1>Payment details</h1>
<br>
Credit Card:<select name="Credit Card">
<option value="Visa">Visa</option>
<option value="Mastercard">Mastercard</option>
<option value="American Express">American Express</option>
</select>
<br><br>
Card Number: <input type="text" id="cardnumber" size="30" />
<br><br>
CCV: <input type="text" id="ccv" size="30" />
<br><br>
Expiry MM/YY:<SELECT id="exMonth" title="select a month" >
<OPTION VALUE="0" SELECTED>--Month--
<OPTION VALUE="01">01
<OPTION VALUE="02">02
<OPTION VALUE="03">03
<OPTION VALUE="04">04
<OPTION VALUE="05">05
<OPTION VALUE="06">06
<OPTION VALUE="07">07
<OPTION VALUE="08">08
<OPTION VALUE="09">09
<OPTION VALUE="10">10
<OPTION VALUE="11">11
<OPTION VALUE="12">12
</SELECT> /
<SELECT id="exYear" title="select a year">
<OPTION VALUE="0" SELECTED>--Year--
<OPTION VALUE="2016">2016
<OPTION VALUE="2017">2017
<OPTION VALUE="2018">2018
<OPTION VALUE="2019">2019
<OPTION VALUE="2020">2020
<OPTION VALUE="2021">2021
<OPTION VALUE="2022">2022
<OPTION VALUE="2023">2023
<OPTION VALUE="2024">2024
<OPTION VALUE="2025">2025
<OPTION VALUE="2026">2026
<OPTION VALUE="2027">2027
</SELECT>
<br><br>
<input type="submit" value="Submit Form" />
<input type="button" onClick="Help()" value="Help">
</form>
</body>
</html>
Here is my java script code
function validateForm()
{
var firstname=document.getElementById("firstname");
var lastname=document.getElementById("lastname");
var postcode=document.getElementById("postcode");
var email=document.getElementById("email");
var cardnumber=document.getElementById("cardnumber");
var ccv=document.getElementById("ccv");
//var message= ""
// message += \n makes all the message display in one box //
if (firstname.value=="")
{
alert("Please enter your first name");
firstname.focus();
return false;
}
if (lastname.value==""){
alert("Please enter your last name");
lastname.focus();
return false;
}
if (postcode.value.length!=4 || isNaN(postcode.value)){
alert("Please enter 4 numbers for your postcode");
postcode.focus();
return false;
}
if (email.value.indexOf("#")== -1 ) {
alert("Please include # symbol");
email.focus();
return false;
}
if (email.value.indexOf(".")== -1 ) {
alert("Please include . symbol");
email.focus();
return false;
}
if (cardnumber.value.length!=16 || isNaN(cardnumber.value)){
alert("Please enter yout 16 digit credit card number");
cardnumber.focus();
return false;
}
if (ccv.value.length!=3 || isNaN(cardnumber.value)){
alert("Please enter yout 3 digit ccv");
ccv.focus();
return false;
}
alert("Thank you for your submission");
return true;
}
function Help() {
var Window1 = window.open("", "", "width=350, height=100");
Window1.document.write("<p>Required fields cannot be left blank<br>The email address must contain an # and a dot<br>The credit card month and year must be valid<br>The postcode must contain four numbers<br>Enter the ccv<p>")
return;
}

Basic JavaScript validation not working

I'm trying to make a simple form with JavaScript validation. It has four fields: title, email address, rating and comments. As far as I know, the code I have here should work to validate the form and I should not be allowed to submit it but whenever I press the submit button none of the prompts appear and the browser submits the form. Could someone let me know where I am going wrong please? I'd imagine there is a simple solution or something I am forgetting but I'm pretty new to this so apologies if it's something very obvious.
The HTML and JavaScript code is:
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var e=document.forms["review"]["Title"].value;
var s=document.forms["review"]["Email"].value;
var t=document.forms["review"]["Rating"].value;
var c=document.forms["review"]["Comments"].value;
var atsym=s.indexOf("#");
var dotsym=s.lastindexOf(".");
if (e==null || e=="")
{
document.getElementById("valAlert").innerHTML="Please Enter a Title";
return false;
}
else if (s==null || s=="" || atsym<1 || dotsym<atsym+2 || dotsym+2>=s.length)
{
document.getElementById("valAlert").innerHTML="That is not a valid email address!";
return false;
}
else if (t=="0")
{
document.getElementById("valAlert").innerHTML="You must enter a rating";
return false;
}
else if (c==null || c=="")
{
document.getElementById("valAlert").innerHTML="You need to enter some kind of comment.";
return false;
}
else
{
alert ("Your review of " + t + "has been submitted!");
}
}
</script>
</head>
<body>
<div id="valAlert"></div>
<form name="review" onsubmit="return validateForm()">
<fieldset>
Enter Title:
<input type="text" name="Title">
</br>
</br>
Enter Email Address:
<input type="text" name="Email">
</br>
</br>
Please Enter Your Rating:
<select name="Rating">
<option value="0">(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
</br>
</br>
<textarea name="Comments" rows="8" colspan="40">Comments:</textarea>
</fieldset>
</br>
</br>
<fieldset>
<input class="button" type="submit" value="Submit"/>
</fieldset>
</form>
</body>
please make a null value check before doing the operations like below
var dotsym=s.lastindexOf(".");
Add the null check for variable 's'.Please check the function naming convention below
obj.lastindexOf(); TO obj.lastIndexOf(".");
You’ve said there were no errors, but you might just be missing them when the form submits and the console is cleared.
If you’re using Chrome/Chromium, you can enable breaking on exceptions in the Sources tab of the developer tools (the icon on the far right should be purple or blue):
In Firefox, it’s in the Debugger Options menu:
As #Rajesh says, the casing you have on lastindexOf is wrong; it should be lastIndexOf.
Now, let’s fix everything else up, starting with formatting:
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var e = document.forms["review"]["Title"].value;
var s = document.forms["review"]["Email"].value;
var t = document.forms["review"]["Rating"].value;
var c = document.forms["review"]["Comments"].value;
var atsym = s.indexOf("#");
var dotsym = s.lastIndexOf(".");
if (e == null || e == "")
{
document.getElementById("valAlert").innerHTML = "Please Enter a Title";
return false;
}
else if (s == null || s == "" || atsym < 1 || dotsym < atsym + 2 || dotsym + 2 >= s.length)
{
document.getElementById("valAlert").innerHTML = "That is not a valid email address!";
return false;
}
else if (t == "0")
{
document.getElementById("valAlert").innerHTML = "You must enter a rating";
return false;
}
else if (c == null || c == "")
{
document.getElementById("valAlert").innerHTML = "You need to enter some kind of comment.";
return false;
}
else
{
alert("Your review of " + t + " has been submitted!");
}
}
</script>
</head>
<body>
<div id="valAlert"></div>
<form name="review" onsubmit="return validateForm()">
<fieldset>
Enter Title:
<input type="text" name="Title" />
</br>
</br>
Enter Email Address:
<input type="text" name="Email" />
</br>
</br>
Please Enter Your Rating:
<select name="Rating">
<option value="0">(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
</br>
</br>
<textarea name="Comments" rows="8" colspan="40">Comments:</textarea>
</fieldset>
</br>
</br>
<fieldset>
<input class="button" type="submit" value="Submit" />
</fieldset>
</form>
</body>
You’re missing a DTD and a closing </html>, so add those:
<!DOCTYPE html>
<html>
…
</html>
Next, </br> doesn’t exist. It’s <br />.
<form name="review" onsubmit="return validateForm()">
<fieldset>
Enter Title:
<input type="text" name="Title" />
<br />
<br />
Enter Email Address:
<input type="text" name="Email" />
<br />
<br />
Please Enter Your Rating:
<select name="Rating">
<option value="0">(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
<br />
<br />
<textarea name="Comments" rows="8" colspan="40">Comments:</textarea>
</fieldset>
<br />
<br />
<fieldset>
<input class="button" type="submit" value="Submit" />
</fieldset>
</form>
Here:
var e = document.forms["review"]["Title"].value;
var s = document.forms["review"]["Email"].value;
var t = document.forms["review"]["Rating"].value;
var c = document.forms["review"]["Comments"].value;
the properties are valid JavaScript identifiers, so you can write them with the dot syntax:
var e = document.forms.review.Title.value;
var s = document.forms.review.Email.value;
var t = document.forms.review.Rating.value;
var c = document.forms.review.Comments.value;
You should probably give them clearer names, too; I think you used the wrong one in that last alert, and this will help:
var title = document.forms.review.Title.value;
var email = document.forms.review.Email.value;
var rating = document.forms.review.Rating.value;
var comments = document.forms.review.Comments.value;
Next, you don’t need elses when you’re returning from the if case no matter what, so you can drop those. The values of text inputs can never be null, so stop checking for those. It’ll also save some typing (or copying) to keep valAlert as a variable.
var atsym = email.indexOf("#");
var dotsym = email.lastindexOf(".");
var valAlert = document.getElementById("valAlert");
if (title === "") {
valAlert.innerHTML = "Please Enter a Title";
return false;
}
if (atsym < 1 || dotsym < atsym + 2 || dotsym + 2 >= s.length) {
valAlert.innerHTML = "That is not a valid email address!";
return false;
}
if (rating == "0") {
valAlert.innerHTML = "You must enter a rating";
return false;
}
if (comments == "") {
valAlert.innerHTML = "You need to enter some kind of comment.";
return false;
}
alert("Your review of " + title + " has been submitted!");
Voilà! But wait; there’s more. The best things in life web development don’t need JavaScript, and this is no exception.
<!DOCTYPE html>
<html>
<head>
<title>HTML5 validation</title>
</head>
<body>
<form>
<fieldset>
<label>
Enter title:
<input type="text" name="title" required />
</label>
<label>
Enter e-mail address:
<input type="email" name="email" required />
</label>
<label>
Please enter your rating:
<select name="rating" required>
<option>(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
</label>
<textarea name="comments" rows="8" cols="40" placeholder="Comments" required></textarea>
</fieldset>
<fieldset>
<button class="button">Submit</button>
</fieldset>
</form>
</body>
</html>
I beg to differ on your comments. You are getting console errors. Specially, it is erroring out whenever you try to run the parsers on s and s is empty. You need to move the logic into the if clause AFTER you have verified it has a value:
else if (s == null || s == "") {
document.getElementById("valAlert").innerHTML = "Please enter an email address";
return false;
}
else if (s.indexOf("#") < 1 || s.lastindexOf(".") < s.indexOf("#")+ 2 || s.lastindexOf(".")+ 2 >= s.length) {
document.getElementById("valAlert").innerHTML = "This is not a valid email address!";
return false;
}
Here is a Fiddle

Categories

Resources