Javascript form date check - javascript

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;
}

Related

How do I make error messages show on the webpage? [duplicate]

This question already has answers here:
HTML5 form required attribute. Set custom validation message?
(17 answers)
Closed 1 year ago.
function validate() {
var errMsg = "";
var result = true;
var fname = document.getElementById("fname").value;
if (!fname.match(/^[a-zA-Z]+$/)) {
errMsg += "Please enter your first name correctly.\n";
result = false;
}
var lname = document.getElementById("lname").value;
if (!lname.match(/^[a-zA-Z]+$/)) {
errMsg += "Please enter your last name correctly.\n";
result = false;
}
var email = document.getElementById("email").value;
if (!email.match(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$/)) {
errMsg += "Please enter your email correctly.\n";
result = false;
}
var streetname = document.getElementById("streetname").value;
if (!streetname.match(/^[a-zA-Z0-9\s]+$/)) {
errMsg += "Please enter your street name correctly.\n";
result = false;
}
var suburb = document.getElementById("suburb").value;
if (!suburb.match(/^[a-zA-Z\-]+$/)) {
errMsg += "Please enter your suburb correctly.\n";
result = false;
}
var phone = document.getElementById("phone").value;
if (!phone.match(/[0-9]{9}/)) {
errMsg += "Please enter your phone number correctly.\n";
result = false;
}
var gender = document.getElementById("gender").value;
var start = document.getElementById("start").value;
var skill = document.getElementById("skill").value;
var other = document.getElementById("other").value;
var otherbox = document.getElementById("otherbox").value;
var postcode = document.getElementById("postcode").value;
var state = document.getElementById("state").options[
document.getElementById("state").selectedIndex
].text;
var regex;
//VIC = 3 OR 8, NSW = 1 OR 2 ,QLD = 4 OR 9 ,NT = 0 ,WA = 6 ,SA=5 ,TAS=7 ,ACT= 0.
switch (state) {
case "Please Select":
return false;
case "VIC":
regex = new RegExp(/(3|8)\d+/);
break;
case "NSW":
regex = new RegExp(/(1|2)\d+/);
break;
case "QLD":
regex = new RegExp(/(4|9)\d+/);
break;
case "NT":
regex = new RegExp(/0\d+/);
break;
case "WA":
regex = new RegExp(/6\d+/);
break;
case "SA":
regex = new RegExp(/5\d+/);
break;
case "TAS":
regex = new RegExp(/7\d+/);
break;
case "ACT":
regex = new RegExp(/0\d+/);
break;
}
if (!postcode.match(regex)) {
errMsg = errMsg + "State and postcode do not match\n";
result = false;
}
if (errMsg) {
alert(errMsg);
}
if (result) {
storeBooking(
fname,
lname,
start,
email,
gender,
phone,
streetname,
suburb,
state,
postcode,
other,
otherbox
);
}
return result;
}
<form action="https://mercury.swin.edu.au/it000000/formtest.php" method="post" id="regform">
<p>Your Name: <span id="job1"></span></p>
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name.." required="required" maxlength="25" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name.." required="required" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">
<label for="start">Date of birth:</label>
<input type="date" id="start" required="required" name="date of birth" value="2021-10-04" />
<br>
<br>
<label for="gender"> Select you gender</label>
<br>
<br>
<select name="gender" id="gender" required="required">
<option value="" selected>Please Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
<label for="streetname">Street Address</label>
<input type="text" id="streetname" name="streetname" required="required" placeholder="Your street name..." maxlength="40" />
<label for="suburb">Suburb/Town</label>
<input type="text" id="suburb" name="suburb" required="required" placeholder="Your suburb/town..." maxlength="40">
<label for="state">Choose a state:</label>
<br>
<select name="state" id="state" required="required">
<option value="">Please Select</option>
<option value="VIC">VIC</option>
<option value="NSW">NSW</option>
<option value="QLD">QLD</option>
<option value="NT">NT</option>
<option value="WA">WA</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="ACT">ACT</option>
</select>
<br>
<br>
<label for="postcode">Postcode</label>
<input type="text" id="postcode" name="postcode" required="required" placeholder="Your postcode..." maxlength="4" minlength="4" pattern="^[0-9]{4}$">
<label for="email">Email Address</label>
<input type="text" id="email" name="emailadd" placeholder="Your email address.." required="required">
<label for="phone">Phone Number</label>
<input type="text" id="phone" name="phonenumb" placeholder="e.g. 0451124561" minlength="8" maxlength="12" required="required">
<br>
<input type="submit" value="Apply">
<br>
<br>
<input type="submit" id="cancelpurchase" value="Cancel Application"></input>
</form>
How do I make it so that the error message shows up on the actual webpage, rather than an alert box, next to the input? I can't seem to find anything online about changing the default way an error message shows up. If you need less/more information, please suggest that to me.
Note: no jQuery or inline JavaScript.
You can make a <div id="popup"> Error message </div> with display: none and position: fixed and instead of alertion make this div visible document.querySelector('#popup').style.display = 'block' and a close button in it to close this popup
You appear to be showing the error message with the following code:
if (errMsg) {
alert(errMsg);
}
If you instead get a reference to an element,
e.g
var tgtElem = document.getElementById(textStringIdGoesHere);
You can then display the message by setting its textContent,
e.g
tgtElem.textContent = errMsg;

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>

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

Javascript Validation doesn't work

I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
HTML:
<form name="myForm" class="appnitro" onsubmit="return validateForm()" action="mysql_connection.php" method="post">
<div class="form_description">
<h2>Patient Record</h2>
<p></p>
</div>
<ul>
<li id="li_1">
<label class="description" for="element_1">&nbspName</label>
<span>
<td width="68%"><input size="15" maxlength="30" class="input" type="text" name="Fname" id="Fname"></td>
<label>First</label>
</span>
<span>
<td width="68%"><input size="15" maxlength="30" class="input" type="text" name="Lname" id="Lname"></td>
<label>Last</label>
</span>
<li class="buttons">
<label class="description" for="element_1">&nbspGender</label>
<span>
<tr>
<select name="Gender">
</tr>
</span>
<option value="Select">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<li class="buttons">
<label class="description" for="element_3">&nbspAge</label>
<span>
<tr>
<select name="Age">
</tr>
</span>
<script type="text/javascript">
listAge()
</script>
</select>
<li class="buttons">
<label class="description" for="element_3">&nbspPhone Number</label>
<span>
<td width="68%"><input size="25" maxlength="50" class="input" type="text" name="Phone" id="Phone"></td>
</span>
<li class="buttons">
<label class="description" for="element_3">&nbspEmail ID</label>
<span>
<td width="68%"><input size="25" maxlength="50" class="input" type="text" name="Email" id="Email"></td>
</span>
<li class="buttons">
<label class="description" for="element_3">&nbspAddress</label>
<span>
<td><textarea cols="25" rows="3" class="input" name="Address" id="Address"></textarea></td>
</span>
<li class="buttons">
<label class="description" for="element_3">&nbspReason For Visit</label>
<span>
<td><textarea cols="25" rows="3" class="input" name="Reason" id="Reason"></textarea></td>
</span>
<li class="buttons">
<label class="description" for="element_3">&nbspAttending Doctor</label>
<span>
<td width="68%"><input size="25" maxlength="50" class="input" type="text" name="Doctor" id="Doctor"></td>
</span>
<li class="buttons">
<input type="submit" value="Submit" />
<input type="reset" value="Reset">
</li>
</ul>
</form>
Javascript:
<script>
function validateForm() {
var Fname = document.forms["myForm"]["Fname"].value;
var Lname = document.forms["myForm"]["Lname"].value;
var Phone = document.forms["myForm"]["Phone"].value;
var Address = document.forms["myForm"]["Address"].value;
var Reason = document.forms["myForm"]["Reason"].value;
var Doctor = document.forms["myForm"]["Doctor"].value;
var email = document.forms["myForm"]["email"].value;
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (Fname == null || Fname == "") {
alert("First name must be filled out");
return false;
}
if (Lname == null || Lname == "") {
alert("Last name must be filled out");
return false;
}
if (Phone == null || Phone == "") {
alert("Phone Number must be filled out");
return false;
}
if (Address == null || Address == "") {
alert("Address must be filled out");
return false;
}
if (Reason == null || Reason == "") {
alert("Reason for Visit must be filled out");
return false;
}
if (Doctor == null || Doctor == "") {
alert("Attending Doctor must be filled out");
return false;
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
}
function listAge() {
var i = 1;
for (i = 1; i <= 100; i++) {
document.write("<option value=" + i + ">" + i + "</option>");
}
}
</script>
Your HTML is hideously invalid. Odds are that the browser is trying to perform error recovery and doing things like moving the <form> element outside the table (assuming there is a table, it doesn't show up in your code but you have table data cells in it) so that the submit button is no longer inside it and does not try to submit the form. (This is a known problem with trying to interleave forms a table rows).
Use a validator to find your errors then fix them.
#Quentin is right, you need to clean your HTML code and javascript code.
But you have an error in your Javascript. You need to write a capital E for the Email field. It is case sensitive.
Try with this :
var email = document.forms["myForm"]["Email"].value;
Why not directly use the ID attribute of the element as if you put an ID inside any element it is always preferred to keep it unique. So you can use document.getElementById("ID").value; to get the value of an individual element. Like this :
var firstName = document.getElementById("firstNameTextBox").value;
if(firstName == ''){
message.innerHTML = "First Name is required";
}
I have a demo that you should try.
Demo
Add this JavaScript code and it should word
function validateForm() {
var Fname = document.forms["myForm"]["Fname"].value;
var Lname = document.forms["myForm"]["Lname"].value;
if (Fname == null || Fname == "") {
alert("First name must be filled out");
return false;
}
if (Lname == null || Lname == "") {
alert("Last name must be filled out");
return false;
}
if (Phone == null || Phone == "") {
alert("Phone Number must be filled out");
return false;
}
if (Address == null || Address == "") {
alert("Address must be filled out");
return false;
}
if (Reason == null || Reason == "") {
alert("Reason for Visit must be filled out");
return false;
}
if (Doctor == null || Doctor == "") {
alert("Attending Doctor must be filled out");
return false;
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
}
function listAge() {
var i = 1;
for (i = 1; i <= 100; i++) {
document.write("<option value=" + i + ">" + i + "</option>");
}
}
I believe the problem is that you try to take some values from fields that not exists at least from the code that you provided! Just copy the code above and it should work for sure!

Categories

Resources