I am trying to validate the form input but my validation is not working.
The string must have at least one letter or digit,
an integer should be between 0-11 and should pick at least one fruit.
But even if i dont enter any input,
it just go to the input_ok.html file.
It needs to pop-up the error window.
Here is my code:
function validateInput() {
var str = myForm.inputString.value;
var nbrStr = myForm.inputInteger.value;
var nbr = parseInt(nbrStr);
var fruit = myForm.fruit.value;
if (str != "" && nbrStr != "" && fruit != "" && !isNaN(nbr) && nbr < 11) {
return true;
} else {
var msg = "";
var strError = false;
if (str == "") {
msg += "\nPlease enter a string with at least one letter or digit";
strError = true;
}
if (nbrStr == "") {
msg += "\nPlease enter an integer in the range 0-11";
} else if (isNaN(nbr)) {
msg += "\nPlease enter an integer";
} else if (nbr > 11) {
msg += "\nPlease enter an integer less than 11";
}
if (strError) {
myForm.inputString.focus();
} else {
myForm.inputInteger.focus();
}
alert(msg);
}
return false;
}
<body>
<h1>Week 08, Exercise 01</h1>
<form action="week08_01servlet"
method="post"
name="myForm"
onsubmit="return validateInput();">
<p>Please enter the following information,
and then click the submit button.</p>
<p class="indent">A string with at least one letter or digit
<input type="text" name="inputString">
<br>An integer in the range 0-11
<input type="text" name="inputInteger">
<br>Pick a fruit <select name="fruit">
<option value="---">---
<option value="apple">apple
<option value="banana">banana
<option value="cherry">cherry
<option value="pear">pear
</select></p>
<p><input type="submit" value="Submit"></p>
<input type="hidden" name="command" value="do_it">
</form>
</body>
This is clearly homework, but I beleave every question deservers an answer. Valid xhtml5, javascript checked with jslint and compressed with ajaxmin. Enjoy.
Also, you might want to read ppks Introduction to Forms.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Week 08, Exercise 01</title>
<link rel="stylesheet" href="Week08_01.css">
<script>
function validateInput(c){var f=c.inputString.value,d=c.inputInteger.value,b=parseInt(d,10),g=c.fruit.value;if(f!==""&&d!==""&&g!==""&&!isNaN(b)&&b>=0&&b<11)return true;else{var a="",e=false;if(f===""){a+="\nPlease enter a string with at least one letter or digit";e=true}if(d==="")a+="\nPlease enter an integer in the range 0-11";else if(isNaN(b))a+="\nPlease enter an integer";else if(b<=0)a+="\nPlease enter a positive integer";else if(b>11)a+="\nPlease enter an integer less than 11";if(e)c.inputString.focus();else c.inputInteger.focus();alert(a);return false}}
</script>
</head>
<body>
<h1>Week 08, Exercise 01</h1>
<form action="week08_01servlet"
method="post"
name="myForm"
onsubmit="return validateInput(this);">
<p>Please enter the following information,
and then click the submit button.</p>
<p class="indent">A string with at least one letter or digit
<input type="text" name="inputString" />
<br>An integer in the range 0-11
<input type="text" name="inputInteger" />
<br />Pick a fruit <select name="fruit">
<option value="---">---</option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="cherry">cherry</option>
<option value="pear">pear</option>
</select></p>
<p><input type="submit" value="Submit">
<input type="hidden" name="command" value="do_it"></p>
</form>
</body>
</html>
Related
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>
so I've created a form. I'm trying to use JavaScript to validate fields. When I press submit, it does nothing. It just sends me to a page saying 'Your file was not found.' I do realize that the code is mostly HTML and not JS. I've been testing as I'm going and it's not working already. Any help is appreciated
Here is my code:
function validateForm() {
var firstname = document.myForm.fname.value;
if (firstname === "" || firstname === " ") {
alert("First name is empty!");
return false;
}
var middlename = document.myForm.middle.value;
if (middle == "" || middle == " ") {
alert("Middle name is empty");
return false;
}
}
function validateForm() {
var firstname = document.myForm.fname.value;
if (firstname === "" || firstname === " ") {
alert("First name is empty!");
return false;
}
var middlename = document.myForm.middle.value;
if (middle == "" || middle == " ") {
alert("Middle name is empty");
return false;
}
var lastname = document.myForm.lname.value;
if (lastname == "" || lastname == " ") {
alert("Last name is empty");
return false;
}
}
<!DOCTYPE html>
<html>
<head>
<title>My form validation</title>
</head>
<body>
<form name="myForm" action="fakeFormCheck.php" onsubmit="validateForm()" method="post">
<fieldset>
*First Name:
<input type="text" name="fname">
<br><br>
Middle/Initial:
<input type="text" name="middle">
<br><br>
*Last Name:
<input type="text" name="lname">
<br><br>
*Email:
<input type="text" name="email">
<br><br>
Phone:
<input type="number" name="number">
<br><br>
</fieldset>
<br>
<fieldset>
*Reason:
<select name="choice">
<option value="Information">Infor reques</option>
<option value="feedback">Feedback</option>
<option value="other">Other</option>
</select>
<br><br>
*Message: <br>
<textarea name="message" rows="7" cols="30">
</textarea>
</fieldset>
<input type="submit" value="Send">
<input type="reset" value="Clear">
</form>
</body>
</html>
Add preventDefault() to the validateForm function & return true once the form is valid
function validateForm(e) {
e.preventDefault();
var firstname = document.myForm.fname.value;
if (firstname === "" || firstname === " ") {
alert("First name is empty!");
return false;
}
var middlename = document.myForm.middle.value;
if (middlename == "" || middlename == " ") {
alert("Middle name is empty");
return false;
}
}
<form name="myForm" action="fakeFormCheck.php" onsubmit="validateForm(event)" method="post">
<fieldset>
*First Name:
<input type="text" name="fname">
<br><br> Middle/Initial:
<input type="text" name="middle">
<br><br> *Last Name:
<input type="text" name="lname">
<br><br> *Email:
<input type="text" name="email">
<br><br> Phone:
<input type="number" name="number">
<br><br>
</fieldset>
<br>
<fieldset>
*Reason:
<select name="choice">
<option value="Information">Infor reques</option>
<option value="feedback">Feedback</option>
<option value="other">Other</option>
</select>
<br><br> *Message: <br>
<textarea name="message" rows="7" cols="30">
</textarea>
</fieldset>
<input type="submit" value="Send">
<input type="reset" value="Clear">
</form>
Try attaching the handler in Javascript rather than inline-eval-HTML, and using preventDefault to prevent the default form submission.
<form name="myForm" action="fakeFormCheck.php" method="post">
and
document.querySelector('form[name="myForm"]').addEventListener('submit', (e) => {
// do tests
if (invalid) {
// something is invalid, prevent the default action of submitting the form:
e.preventDefault();
}
// else the form will submit by default
});
Use return in onsubmit="validateForm()" for example onsubmit="return validateForm()". second thing you are taking the middle name in middlename variable but your checking with some other varible if (middle == "" || middle == " ") {
var myForm = document.getElementById("form");
document.bgColor="#FFFFCC"; //page styling
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){ //validate post code
alert("Your post code must be 4 numbers in length");
postcode.focus();
return false;
}
if (isNaN(document.getElementById("postcode").value)){
alert("Your postcode can not contain letters");
postcode.focus();
return false;
}
if (email.value.length<5 || email.value.indexOf("#")== -1){ //validate email
alert("Your email must not be less than 5 charcters in length, it must contain an # and a .");
email.focus();
return false;
}
if (email.value.indexOf(".")== -1){
alert("Your email must not be less than 5 charcters in length, it must contain an # and a .");
email.focus();
return false;
}
if (cardtype.value == ""){
alert("Please enter your card type");
email.focus();
return false;
}
if (cardnumber.value.length!=16){ //validate card number length
alert("Your card number must be 16 numbers in length");
cardnumber.focus();
return false;
}
if (isNaN(document.getElementById("cardnumber").value)){
alert("Your card number can not contain letters");
cardnumber.focus();
return false;
}
if (ccv.value.length!=3){ //validate ccv number length
alert("Your ccv must be 3 numbers in length");
ccv.focus();
return false;
}
if (isNaN(document.getElementById("ccv").value)){
alert("Your ccv must be a number");
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: -5%; transform: translateY(5%);}
#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: -190%; transform: translateY(190%);}
<!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) THEN
OUTPUT error in postcode
RETURN false
ENDIF
IF (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 email.value.indexOf(".")== -1) THEN
OUTPUT error in email
RETURN false
ENDIF
IF (cardnumber.length!=16) THEN
OUTPUT error in cardnumber
RETURN false
ENDIF
IF (isNaN(document.getElementById("cardnumber").value))
OUTPUT error in cardnumber
RETURN false
ENDIF
IF (ccv.length !=3) THEN
OUTPUT error in ccv
RETURN false
ENDIF
IF (isNaN(document.getElementById("ccv").value))
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()">
<script src="../js2/assignment.js"></script>
<div id="Div1">
<h3>Order Form</h3>
<fieldset>
<legend>Enter your Details here</legend></br>
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="4" />
<br /><br />
Email: <input type="text" id="email" size="30" />
<br/><br/>
</fieldset>
<!--<table>
<tr>
<td><label for="FirstName">First Name</label></td>
<td><input type="text" name="FirstName" id="firstname" size="30" required="required" autofocus /></td>
</tr>
<tr>
<td><label for="LastName">Last Name</label></td>
<td><input type="text" name="LastName" 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>-->
<h3>Payment Details</h3>
<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="18"/>
<br/></br>
CCV <input type="text" id="ccv" size="3"/>
<br/></br>
Expiry MM/YY <select id="month" onsubmit="checkDate()">
<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" onsubmit="checkDate()">
<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>
I have a JavaScript assignment to write a basic form and validate user input, I have gotten to the stage where I have written a function to check expiry date of credit card (The month and year have to be checked against the current date) then a confirmation to the user of a successful submission.I also want to increase the size of the 'help' and 'submit' buttons and move them up vertically to the bottom of the form. I am having trouble getting this date check to work, I will attach my work so far,any help would be appreciated, thanks.
You need to check the year first and then the month.
if (year > expiryYear) //check if the current year has not expired
{
alert("Your card has expired");
month.focus();
return false;
}
if (year == expiryYear)
{
if(month >= expiryMonth) //check if the current month has not expired
{
alert("Your card has expired");
month.focus();
return false;
}
}
Or you you can simply write it as
if (year > expiryYear || ((year == expiryYear && month >= expiryMonth)) //check if the current year has not expired
{
alert("Your card has expired");
month.focus();
return false;
}
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;
}
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