Form validation error. Redirects to error page - javascript

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 == " ") {

Related

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 Validation form onsubmit not returning false

Note : i searched similar questions and still couldn't fix it so i'm asking again.
i have a form and its onsubmit = "return submit()". it checks if textarea is empty. If it is then it returns false but that doesn't work.The action still goes to the next website even if text area is empty.
let firstName = document.querySelector('#firstname');
let lastName = document.querySelector('#lastname');
let password = document.querySelector('#password');
let retypePass = document.querySelector('#repassword');
let radioMale = document.querySelector('#male');
let radioFemale = document.querySelector('#female');
let textArea = document.querySelector('#textarea');
let select= document.querySelector('#select');
let button = document.querySelector('#button');
let form = document.querySelector('#form');
function submit(){
if (textArea.value = "") {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}
}
HTML :`
<div class='wrapper'>
<h1>Registration Form</h1>
<form action="http://google.com" id='form' onsubmit="return submit()">
<input placeholder="First Name" type="text" id='firstname' required>
<span></span>
<br>
<input placeholder="Last Name" type="text" id='lastname' required>
<span></span>
<br>
<input placeholder="Password" type="text" id='password' required>
<span></span>
<br>
<input placeholder="Retype Password" type="text" id='repassword' required>
<span></span>
<br>
<input placeholder="Phone Number" type="tel" id='tel' >
<br>
<div class='radio'>
<h4>Selector Your Gender</h4>
<input type='radio'name='same' id='male'>Male
<input type='radio'name='same' id='female'>Female
</div>
<p style="margin:5px 0px;color:white">ADDRESS:</p>
<textarea id='textarea'></textarea>
<span></span>
<p style="margin:5px 0px;color:white">Country:</p>
<select type='country' style="width:84%" id='select'>
<option>England</option>
<option>Japan</option>
<option>America</option>
<option>France</option>
<option>NetherLands</option>
</select>
<br><br>
<input type='submit' value='submit'>
</form>
</div>
Your if systax was wrong:
if (textArea.value = "")
It should be:
if (textArea.value == "")
You must change the name of the function
Example
<form action="http://google.com" id='form' onsubmit="return validate()">
and
function validate() {
if (textArea.value == "") {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}
}
try
if (!textArea.value) {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}
OR
if (textArea.value == '') {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}

How to make a submit button work on a questionnaire

I am making a health questionnaire, I am having a few problems with it. The main problem is the else section. Can someone tell me why it isn't working and help me sort it?
The code I have is:
Assignment 4
Health Questionnaire
<body>
<form name="form1">
Please enter the following details: <p>
First Name: <br>
<input type="text" name="txtFirstName"> size="20" maxlength="20"> <p>
Surname: <br>
<input type="text" name="txtSurName"> size="30" maxlength="20"> <p>
Age: <br>
<input type="text" name="txtAge" size="3" maxlength="3"> <p>
Address Line 1: <br>
<input type="text" name="txtAddressline1" size="30" maxlength="30"> <p>
Address Line 2: <br>
<input type="text" name="txtAddressline2" size="30" maxlength="30"> <p>
City: <br>
<input type="text" name="txtCity" size="20" maxlength="20"> <p>
County: <br>
<input type="text" name="txtCounty" size="20" maxlength="20"> <p>
Post Code: <br>
<input type="text" name="txtPostCode" size="10" maxlength="10"> <p>
<input type="submit" value="Check Details" name=validateForm
onclick="validateForm_onclick()">
<script type ="text/javascript">
function validateForm_onclick()
{
var myForm = document.form1;
if(myForm.txtAge.value === "" || myForm.txtFirstName.value === ""||
myForm.txtSurName.value === ""|| myForm.txtAddressline1.value === ""||
myForm.txtAddressline2.value === ""|| myForm.txtCity.value === ""||
myForm.txtCounty.value === ""|| myForm.txtPostCode.value === "")
{
alert("Please complete all of the form");
if(myForm.txtFirstName.value ==="")
{
myForm.txtFirstName.focus();
}
else
{
myForm.txtSurName.focus();
}
else
{
myForm.txtFirstName.focus();
}
else
{
myForm.txtAge.focus();
}
else
{
myForm.txtAddressline1.focus();
}
else
{
myForm.txtAddressline2.focus();
}
else
{
myForm.txtCity.focus();
}
else
{
myForm.txtCounty.focus();
}
else
{
myForm.txtPostCode.focus();
}
}
else
{
alert("Thanks for completing the form " + myForm.txtName.value);
myForm.submit();
}
}
</script
</form>
</body>
I need to also keep the sizes on the names but need to hide that from the user.
Can someone give me some advice on how to change this?
Your form does not have a submit button.
Your code:
<input type="button" value="Check Details" name=validateForm
onclick="validateForm_onclick()">
Rectified code:
<input type="submit" value="Check Details" name=validateForm
onclick="validateForm_onclick()">
Also, the long list of else is illegal in JavaScript.
form name=form1 needs to have quotes: form name="form1"
And in case you don't want to use submit but stick to a button, insert this in your javascript:
else
{
alert("Thanks for completing the form " + myForm.txtName.value);
myForm.submit();
}

Validation fails when multiple <form> tags are present in the same HTML document

I have multiple form tags in my html doc and want to validate them. However the validation function won't give any result. Tried
adding name field to the <form> the validation() does not return any result.
When I use validation with only one <form> the result is correct.
here are the two form tags:
<div id="pinfo">
<form>
<fieldset>
<legend>Personal Information</legend>
Name:
<input type="text" name="name" value="Enter name">
<br><br>
Email:
<input type="email" name="eamil" value="Enter email id">
<br><br>
Confirm email id:
<input type="text" name="cemail" value="">
<br><br>
Password:
<input type="password" name="pass" value="">
<br><br>
Confirm password:
<input type="password" name="cpass" value="">
<br><br>
</fieldset>
</form>
</div>
<div id="linfo">
<form>
<fieldset>
<legend>Location and Contact</legend>
Location:
State:
<!more code ahead>
<script>
function validateForm() {
var eid = document.forms["loginform"]["emailid"].value;
if (eid == null || eid == "") {
alert("Email id must be entered.");
return false;
}
var pwd = document.forms["loginform"]["password"].value;
if (pwd == null || pwd == ""){
alert("Please enter the password.");
return false;
}
var p = document.forms["locinfo"]["pno"].value;
if (p == null || p=="") {
alert("Please enter the phone no.");
return false;
}
</script>
Validating Form Fields Using JavaScript in FrontPage
There are some mistakes in your code.
You have not given form name as "loginform" which you are using in validation function.
And second thing you missed is "onsubmit" attribute on form element
Here is working code for you
function validateForm() {
console.log(document.forms["loginform"])
var eid = document.forms["loginform"]["eamil"].value;
if (eid == null || eid == "") {
alert("Email id must be entered.");
return false;
}
var pwd = document.forms["loginform"]["pass"].value;
if (pwd == null || pwd == "") {
alert("Please enter the password.");
return false;
}
/*var p = document.forms["locinfo"]["pno"].value;
if (p == null || p == "") {
alert("Please enter the phone no.");
return false;
}*/
}
<div id="pinfo">
<form method="post" name="loginform" action="/" onsubmit="return validateForm()">
<fieldset>
<legend>Personal Information</legend>
Name:
<input type="text" name="name" value="">
<br><br>
Email:
<input type="email" name="eamil" value="">
<br><br>
Confirm email id:
<input type="text" name="cemail" value="">
<br><br>
Password:
<input type="password" name="pass" value="">
<br><br>
Confirm password:
<input type="password" name="cpass" value="">
<br><br>
<input type="submit" name="submit" />
</fieldset>
</form>
</div>

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