Validation with html form only gives if statement - javascript

No matter how many characters I enter, it only gives the if statement and not the else.
is there a typo I entered somewhere I am not seeing, or does the function not work if there are two inputs?
function valid_Function(){
var x, text;
x = document.getElementById("name").value;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
}
else {
text = "Input OK";
}
document.getElementById("valid").innerHTML = text;
}
form input {
display: block;
margin-top: 10px;
}
form [type="submit"] {
padding: 5px;
border-radius: 5px;
border: none;
background: skyblue;
transition: .5s ease;
}
form [type="submit"]:hover {
box-shadow: 0 2px 5px 2px rgba(92, 228, 252, 0.8);
}
<form action="#">
<input for="fname" id="name" placeholder="First Name" type="text">
<input for="lname" id="name" placeholder="Last Name" type="text">
<input onclick="valid_Function()" type="submit" value="Submit">
</form>
<p id="valid"></p>

The couple issues noted in the comments are causing your code to break.
IDs in HTML need to be unique, so having 2 elements with id="name" will cause problems in JavaScript
Assuming you meant to check the length of first/last names rather than comparing the values to the integers 1 and 10, the code should be checking the .length property in your conditionals.
Assuming you want to run this check separately for each name input, here is the adjusted code to validate first and last name separately. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event for more information about handling form submission events.
document.getElementById('form').addEventListener('submit', function(event) {
event.preventDefault(); // this prevents the form from submitting right away so the rest of the validation can run
var firstName = document.getElementById("first_name").value.trim();
var lastName = document.getElementById("last_name").value.trim();
var text;
if (firstName.length < 1 || firstName.length > 10) {
text = "First name is not valid";
} else if (lastName.length < 1 || lastName.length > 10) {
text = "Last name is not valid";
} else {
text = "Input OK";
}
document.getElementById("valid").innerHTML = text;
return false; // this stops the form from continuing to submit, you may or may not want this line here
});
form input {
display: block;
margin-top: 10px;
}
form [type="submit"] {
padding: 5px;
border-radius: 5px;
border: none;
background: skyblue;
transition: .5s ease;
}
form [type="submit"]:hover {
box-shadow: 0 2px 5px 2px rgba(92, 228, 252, 0.8);
}
<form id="form">
<input for="fname" id="first_name" placeholder="First Name" type="text">
<input for="lname" id="last_name" placeholder="Last Name" type="text">
<input type="submit" value="Submit">
</form>
<p id="valid"></p>

Why not a simple truthy check?
if (!x) {
text = "Input not valid";
}
else {
text = "Input OK";
}
And, if you just want to make sure the length remains less than 10, then
if (!x || x.length> 10) {
text = "Input not valid";
}
else {
text = "Input OK";
}

No matter how many characters I enter, it only gives the if statement and not the else
Yes because isNaN will always return true if you give it a non number string and that's what is happening with you, if you try and input a number between 1 and 9 then your else will be executed.
Your validation works with number type inputs but since you want to validate a text input(name) then it can be done like this
your if statement
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
}
should be
if(x === "" || x.length > 10) {
text = "Input not valid";
}
because you need to check if the input is empty and if it is larger than 10 chars, besides I noticed you have two inputs with the same id!, the id is something unique it's not like classes, so pls change your HTML code

Related

Javascript cannot submit form with empty field validation

I have a small issue with my code not submitting my form. Once I fill out the form and press the submit button, nothing simply happens, it seems like the form is not being submitted. In practice, this code should check whether there are any empty fields and if so, it prompts a message instructing to fill out the fields. If every field filled out, submit the form.
function storeUser() {
var userObject = {};
userObject.username = document.getElementById("username").value;
userObject.email = document.getElementById("inputEmail").value;
userObject.password = document.getElementById("inputPassword").value;
userObject.passwordConfirm = document.getElementById("inputPasswordConfirm").value;
userObject.mobileNumber = document.getElementById("inputNumber").value;
userObject.score = 0;
if (userObject.password !== userObject.passwordConfirm) {
document.getElementById("Warning").innerHTML = "Your password doesn't match.";
return false;
}
if (userObject.username === "") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
}
if (userObject.email === " " ) {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
}
if (userObject.password === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
}
if (userObject.passwordConfirm === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
}
if (userObject.mobileNumber === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
return false;
}
else {
return true;
}
localStorage[userObject.email] = JSON.stringify(userObject);
document.getElementById("Result").innerHTML = "Success! You have registered your account.";
As you most probably noticed, I'm a complete novice to this. Aynone could lead me the right way?
EDIT:
<form class="form-container" name="registerForm" onsubmit="return false">
<p><b>Please fill out all fields to register your account</b></p>
<div class="form-group">
<input type="text" class="form-control" id="username" aria-describedby="username" placeholder="Username" minlength=3 required>
</div>
<div class="form-group">
<input type="email" class="form-control" id="inputEmail" aria-describedby="emailHelp" placeholder="Enter email" required>
</div>
<div class="form-group">
<input type="password" class="form-control" id="inputPassword" placeholder="Password" required>
</div>
<div class="form-group">
<input type="password" class="form-control" id="inputPasswordConfirm" placeholder="Confirm password" required>
</div>
<div class="form-group">
<input type="tel" class="form-control" id="inputNumber" placeholder="Mobile number" pattern="^\s*\(?(020[7,8]{1}\)?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3}\)?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})\s*$" required>
</div>
<button type="submit" onclick="storeUser()" class="btn btn-primary regstrbtn">Register</button>
<p id="Result"></p>
<p id="Warning" style="color: red;"></p>
</form>
Looking at your code I found a number of problems:
Invalid telephone number regexp: you are using the following regexp to validate the telephone number field, but it has a missing character:
^\s*\(?(020[7,8]{1}\)?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3}\)?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})\s*$
// missing ] after 0-9 ^^
(I am going to ignore the fact that the regular expression has placeholder 'Mobile number' yet only accepts landline phone numbers for inner and outer London in the UK.)
You are showing validation error messages if the email, password, confirm-password and telephone number fields contain a single space:
if (userObject.email === " " ) {
You probably want to be comparing the values against an empty string instead:
if (userObject.email === "" ) {
The end of your storeUser() function is as follows:
if (userObject.mobileNumber === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
return false;
}
else {
return true;
}
localStorage[userObject.email] = JSON.stringify(userObject);
document.getElementById("Result").innerHTML = "Success! You have registered your account.";
When do we reach the last two lines, the one that writes to local storage and the one that shows the success message?
If the telephone number field contains a single space, then a warning message appears and the function returns false.
If the telephone number field contains anything other than a single space, the function returns true.
The last two lines are unreachable. They are never executed because the function returns before it gets to them.
What you probably want to do is to get rid of the else clause and add return true; at the bottom, i.e.:
if (userObject.mobileNumber === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
return false;
}
localStorage[userObject.email] = JSON.stringify(userObject);
document.getElementById("Result").innerHTML = "Success! You have registered your account.";
return true;
Inconsistent use of return false;. If the passwords don't match, or the telephone number field isn't filled out, the function returns false. There is no corresponding return false; line for the username, email, password and confirm-password fields. Add this line for each of these fields.
You aren't clearing the warning message if the form is successfully completed. Add the line
document.getElementById("Warning").innerHTML = "";
to the end of your function.
Incidentally you have various pairs of lines
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
but the first line in each pair is unnecessary because the empty-string value you assign to the inner HTML of the warning element is immediately replaced by the warning message assigned in the second line. You can delete the first line of each such pair.
You can simply manage this using HTML5 form field validators, please find below code snippet:
body {
font-family: Helvetica, Arial;
font-size:12px;
}
h1 {
font-size:200%;
}
legend {
padding:0 5px;
text-align:right;
}
fieldset > div {
margin:10px 0;
}
fieldset > legend + div {
margin-top:0;
}
fieldset > div:last-child {
margin-bottom:0;
}
label {
display:inline-block;
width:100px;
}
input {
width:200px;
}
input[type="number"] {
width:30px;
}
div > input[type="submit"] {
background: #ccc;
border:1px solid #999;
width:auto;
}
input:required {
background:hsl(180, 50%, 90%);
border:1px solid #999;
}
input:optional {
background:hsl(300, 50%, 90%);
border:1px dotted hsl(180, 50%, 90%);
}
input:valid,
input:in-range {
background:hsl(120, 50%, 90%);
border-color:hsl(120, 50%, 50%);
}
input:invalid,
input:out-of-range {
border-color:hsl(0, 50%, 50%);
background:hsl(0, 50%, 90%);
}
.help {
display:none;
font-size:90%;
}
input:focus + .help {
display:inline-block;
}
div.submit {
margin-left:100px;
}
<form action="" method="post">
<fieldset>
<legend>Booking Details</legend>
<div>
<label for="name">Name:</label>
<input id="name" name="name" value="" required pattern="[A-Za-z-0-9]+\s[A-Za-z-'0-9]+" title="firstname lastname" aria-required="true" aria-describedby="name-format">
<span id="name-format" class="help">Format: firstname lastname</span>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="" required aria-required="true">
</div>
<div>
<label for="website">Website:</label>
<input type="url" id="website" name="website" value="">
</div>
<div>
<label for="numTickets"><abbr title="Number">No.</abbr> of Tickets:</label>
<input type="number" id="numTickets" name="numTickets" value="" required aria-required="true" min="1" max="4">
</div>
<div class="submit">
<input type="submit" value="Submit">
</div>
</fieldset>
</form>

Validating contact form with javascript

The code below obviously has a lot of errors or some other things missing but I am beginner to JavaScript trying to make my own projects.
I tried to make this contact form with JavaScript validation from my own and a bit with a search but I'm stuck because validation form doesn't work at all. I would appreciate if you help me fixing this, thank you.
let name = document.querySelector('.name');
let email = document.querySelector('.email');
let submit = document.querySelector('.submit');
function validateName() {
if (name === null) {
error.innerHTML = 'Name cannot be blank';
return false;
} else if (name < characters.length < 3) {
error.innerHTML = 'Use more than 3 characters';
return false;
}
}
function validateEmail() {
if (email === null) {
error.innerHTML = 'Email cannot be blank';
return false;
} else if (email < characters.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
return false;
}
}
function submitForm() {
document.querySelector('.submit').submit();
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<input class="name" type="text" placeholder="Your Name">
<br>
<input class="email" type="email" placeholder="Your Email">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<br>
<button class="submit" action="/submit.php" onclick="submitForm()">Submit</button>
</div>
</div>
Well, you only defined validation methods but don't use them, that's why they have no effect.
You should add event listeners like onchange (or oninput, depending on when you'd like to show error messages) to your fields.
For instance:
<input class="name" type="text" placeholder="Your Name" onchange="validateName()">
Actually, you have multiple more problems:
error is undefined: you should create another element and find it in JS
you have to use element.value, not element to access a value of input
you have undefined characters used in a weird way in your checks; to check the length of content, use element.value.length
Here's a snippet with these fixes:
let name = document.querySelector('.name');
let email = document.querySelector('.email');
let submit = document.querySelector('.submit');
let error = document.querySelector('.error');
function validateName() {
if (!name.value) {
error.innerHTML = 'Name cannot be blank';
return false;
} else if (name.value.length < 3) {
error.innerHTML = 'Use more than 3 characters';
return false;
}
}
function validateEmail() {
if (!email.value) {
error.innerHTML = 'Email cannot be blank';
return false;
} else if (email.value.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
return false;
}
}
function submitForm() {
document.querySelector('.submit').submit();
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<input class="name" type="text" placeholder="Your Name" onchange="validateName()">
<br>
<input class="email" type="email" placeholder="Your Email" onchange="validateEmail()">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<div class="error"></div>
<br>
<button class="submit" action="/submit.php" onclick="submitForm()">Submit</button>
</div>
</div>
Moreover, I'd make some more improvements to the code, namely
use event.target inside event handlers instead of calcing the elements globally (note the difference in usage inside html too);
clear the error div when the content is ok!
why multiple return false instead of one in the end of the handler?
you don't use the submit variable, get rid of it; does submitForm do anything useful? (submits on submit??) Not sure, but it seems it should be removed, too
let error = document.querySelector('.error');
function validateName(event) {
let name = event.target;
if (!name.value) {
error.innerHTML = 'Name cannot be blank';
} else if (name.value.length < 3) {
error.innerHTML = 'Use more than 3 characters';
} else {
error.innerHTML = '';
}
return false;
}
function validateEmail(event) {
let email = event.target;
if (!email.value) {
error.innerHTML = 'Email cannot be blank';
} else if (email.value.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
} else {
error.innerHTML = '';
}
return false;
}
function submitForm() {
document.querySelector('.submit').submit();
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<input class="name" type="text" placeholder="Your Name" onchange="validateName(event)">
<br>
<input class="email" type="email" placeholder="Your Email" onchange="validateEmail(event)">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<div class="error"></div>
<br>
<button class="submit" action="/submit.php" onclick="submitForm()">Submit</button>
</div>
</div>
Alot of your syntax and validation methods are off. Few tips: you need to use name.value and email.value to get the values of the elements, you also need to use name.value.length instead of email < characters.length < 5 and change the button type to submit and you can negate having to call it in JS.
Below is a working snippet based on the code you posted. I believe it does what you want.
let error = document.getElementById('error');
function validateName() {
let name = document.getElementById('name');
if (!name.value) {
error.innerHTML = 'Name cannot be blank';
return false;
} else if (name.value.length < 3) {
error.innerHTML = 'Use more than 3 characters on name';
return false;
}
}
function validateEmail() {
let email = document.getElementById('email');
if (!email.value) {
error.innerHTML = 'Email cannot be blank';
return false;
} else if (email.value.length < 5) {
error.innerHTML = 'Use more than 5 characters on email';
return false;
}
}
function submitForm() {
error.innerHTML = ""
validateEmail()
validateName()
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<input id="name" type="text" placeholder="Your Name">
<br>
<input id="email" type="email" placeholder="Your Email">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<br>
<button class="submit" type = "submit" action="/submit.php" onclick="submitForm()">Submit</button>
<div id="error">
</div>
</div>
</div>
You've written your JS function validateName and validateEmails but you aren't calling those functions anywhere. Instead of selecting the .submit button inside of submitForm(), call those functions. The line you have inside of submitForm is doing nothing. onclick() within your HTML handles the calling of the function submitForm(), and submitForm() should then validate your form.
Edit: you can also call validateName and validateEmails when the email or name fields are edited.
Yeah, like what the other contributors said, the validate functions are written well, they just aren't being called.
You can either add them to the onchange property of your input elements, or call it in your submitform function like so:
function validateName() {
if (name === null) {
error.innerHTML = 'Name cannot be blank';
return false;
} else if (name < characters.length < 3) {
error.innerHTML = 'Use more than 3 characters';
return false;
}
return true;
}
function validateEmail() {
if (email === null) {
error.innerHTML = 'Email cannot be blank';
return false;
} else if (email < characters.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
return false;
}
return true;
}
function submitForm(){
if(validateName() && validateEmail()){
//Do whatever submitting entails
}
}
Also remember to add an error div to your html to display the errors, and to create an error querySelector variable like you did with name, email and submit.
You're doing great! Keep up the good work!
Here's something that works to a minimum using your current code. I added comments to explain what is going on. Don't hesitate to ask me for any clarifications. Like you said, code can be improved further but I didn't want to change too much and confuse you.
let name = document.querySelector('.name');
let email = document.querySelector('.email');
let submit = document.querySelector('.submit');
let error = document.querySelector('#error'); //Get's the span in the html where the errors will be shown.
function validateName() {
//Get the text value of name with name.value and care with an empty string.
if (name.value === "") {
error.innerHTML = 'Name cannot be blank';
return false;
//Get the number of character in the value of the name and see if you have less than 3.
} else if (name.value.length < 3) {
error.innerHTML = 'Use more than 3 characters';
return false;
}
}
function validateEmail() {
//Get the text value of name with name.value and compare with an empty string.
if (email.value === "") {
error.innerHTML = 'Email cannot be blank';
return false;
//Get the number of characters in the value of the email and see if you have less than 5.
} else if (email.value.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
return false;
}
}
function submitForm() {
//Instead of calling the function .submit (that doesn't exist). Call the verification functions that you made.
validateName();
validateEmail();
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<span id="error"></span>
<input class="name" type="text" placeholder="Your Name">
<br>
<input class="email" type="email" placeholder="Your Email">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<br>
<button class="submit" action="/submit.php" onclick="submitForm()">Submit</button>
</div>
</div>

Javascript form validation for phone numbers

Trying to create a form with pretty simple validation and I'm curious as to two things.
One; how do I check if a form is empty?
Two; on the phone number field how would I only accept numbers in this format:
xxx-xxxx (where X is a number)
Here is what I have done so far:
HTML:
<form onsubmit="return false" method="post" name="myForm">
<div class="form-block">
<label>Name: </label>
<input type="text" name="name" id="name" />
<span id="name-error" class="error"></span>
</div>
<div class="form-block">
<label>Phone Number: </label>
<input type="text" name="phone" id="phone" />
<span id="phone-error" class="error"></span>
</div>
<input type="submit" id="mysubmit" name="submit" onclick="validate()" />
</form>
CSS:
a, p, h1, h2, h3, h4, h5, h6, li, label, span {
font-family: sans-serif;
}
#mysubmit {
display: block;
margin-top: 10px;
}
span.error {
color: red;
font-weight: bold;
}
.form-block {
display: block;
width: 100%;
margin: 10px 0;
}
label {
display: inline-block;
width: 150px;
text-align: right;
}
JS:
validate = function() {
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
if(/^[a-zA-Z]*$/.test(name)) {
document.getElementById("name-error").innerHTML = "Good.";
} else {
document.getElementById("name-error").innerHTML = "Invalid. Only letters.";
}
if(isNaN(phone)) {
document.getElementById("phone-error").innerHTML = "Can only contain numbers";
} else {
document.getElementById("phone-error").innerHTML = "Good.";
}
};
You can test if the value of a form element is empty by simply checking for an empty string.
I've already posted something that will help you access and iterate through form fields.
// ES5: a very crude validation check
// your form field elements should share a class in order to collect them all
var formElements = document.querySelectorAll('.your-form-field-class');
// set a flag to keep track of whether you have an empty field
var containsEmptyField = false
i,
l = formElements.length;
for (; i < l; i++) {
if (formElements[i].value === '') {
containsEmptyField = true;
// do something in response to an empty field
// the break is to stop looping since you've found
// a match
break;
}
}
// ES6: a very crude validation check
const formElements = document.querySelector('#some-form').elements;
let containsEmptyField = false;
for (let element of formElements) {
if (element.value === '') {
containsEmptyField = true;
break;
}
}
I haven't tested it properly, but the regex for the phone number, might look something like this:
(/^(\d){3,3}\-(\d){4,4}$/).test(someNumber)
// returns true if value matches or false if it doesn't

Check the contents of the edit field

I have on my website input type="text" and i trying to write code, that can check when field is empty.
if (number>0)document.getElementById("score").innerHTML="+";
else if (number<0)document.getElementById("score").innerHTML="-";
else if (number==0)document.getElementById("score").innerHTML="0";
else document.getElementById("score").innerHTML="this is not a number";
And when the field is null, it still shows that "0" is entered.
____edit
var number = document.getElementById("field").value;
<input type="text" id="field">
Here is a working solution that shows nothing in the score div when then input field is empty. (You can change it to show a message if you want.)
var score = document.getElementById('score');
document.getElementById('field').addEventListener('keyup', checkNum);
function checkNum() {
var number = parseInt(document.getElementById('field').value);
if (number>0) score.innerHTML="+";
else if (number<0) score.innerHTML="-";
else if (number==0) score.innerHTML="0";
else if (document.getElementById('field').value=="") score.innerHTML="";
else score.innerHTML="this is not a number";
}
#score {
display: inline-block;
border: 2px solid red;
border-radius: 4px;
font-weight: 700;
padding: 4px;
}
<input type="text" id="field">
<br><br>
<div id="score"></div>

Why isn't my form submit button not going to a next page when I click on it?

I am trying to figure out why the form's "submit this form" button is not taking me to another HTML page I specified in the <form ... action="submit form.html" method="get"> attribute and not only that but when I put wrong first names, email addresses, and order numbers, and date of orders, it doesn't return JavaScript messages I specified in my if-else codes using JavaScript.
Here is the JavaScript code I use on the form.
var $ = function (id)
{
return document.getElementById(id);
}
var submitForm = function()
{
var FirstName= $("firstName").value;
var OrderNumber= $("orderNumber").value;
var DateOfOrder= $("date_of_order").value;
var emailAddress= $("email_address").value;
var isValid=true;
if(FirstName !== "Cherry", "Micheal", "Sandra", "Cookie")
{
$("firstname_error").firstChild.nodeValue=
"This person does not exist.";
isValid=false;
} else{ $("firstname_error").firstChild.nodeValue="";}
if(OrderNumber !== 3134, 4234, 9234, 3566)
{
$("orderNumber_error").firstChild.nodeValue="Invalid Order Number.";
isValid=false;
} else{ $("orderNumber_error").firstChild.nodeValue="";}
if(DateOfOrder !=='12-07-23', '15-04-24', '16-02-01', '14-01-12')
{
$("date_of_order_error").firstChild.nodeValue="Date doesn't exist in
system";
isValid=false;
} else{ $("date_of_order_error").firstChild.nodeValue="";}
if(emailAddress !="cherryjackson#gmail.com", "michealroberts#yahoo.com",
"sandrabell#hotmail.com", "cookiedanny#outlook.com")
{
$("email_address_error").firstChild.nodeValue="The email doesn't exist";
isValid=false;
} else{ $("email_address_error").firstChild.nodeValue="";}
if(isValid)
{
//submit the form if all entries are valid
$("cookie_form").submit();
}
}
window.onload = function()
{
$("form_submission").onclick = submitForm;
$("email_address").focus();
}
body{
background-color:#FBFBE8;
}
/* Tells HTML5 to find the font-type-face that my OS has and then use that for heading 1
and also centers the first heading */
h1{
font-family:Arial, Helvetica, sans-serif;
text-align:center;
}
/* Tells HTML5 to use any of the font-types for my first paragraph in HTML source file
if one is not available. Also clears some white space
from the left margin of the paragraph and finally tells it to give that paragraph
a size of 20 pixels. */
p{
font-family:Arial, Helvetica, sans-serif;
padding: 20px;
font-size:20px;
}
label{
float: left;
width: 11em;
text-align: right;
font-family:Arial, Helvetica, sans-serif;
color:#800000;
}
input{
margin-left: 1em;
margin-bottom:.5em;
}
span{
color: red;
}
.field_set_1{
border-color: purple;
border-style: solid;
}
#form_submission{
background-color:black; color:white;
}
legend{
font-family:Arial, Helvetica, sans-serif;
color:blue;
}
/* All of the classes are just for positioning and floating the four
same images around the form input information */
.Wrap1{
float:right;
margin:40px;
width:200px;
height:200px;
}
.Wrap2{
float:left;
margin:40px;
width:200px;
height:200px;
}
.clearfix {
clear: both;
}
<!DOCTYPE html>
<html>
<head>
<title>Cookie Order Form </title>
<link rel="stylesheet" href="First_Design.css">
<script src="cookieform.js"></script>
</head>
<body>
<h1>Cookie Order Form</h1>
<p>This form is a cookie order form for customers that purchased cookies from
Daron's Cookies Company and the following below must be filled out in order for each
customer to receive a final message that tells them when their order will be ready.</p>
<IMG class="Wrap1" SRC="cookie.gif" alt="cookie">
<IMG class="Wrap2" SRC="cookie.gif" alt="cookie2">
<!--The customer will be sent to the HTML page named "submit form.html" after they
click the "Submit this Form" button. The code below does this. -->
<div>
<form id="cookie_form" name="cookie_form" action="submit form.html" method="get">
<fieldset class="field_set_1">
<!-- Below sets the title of the form-->
    <legend>Customer Order Form Information:</legend>
<!-- Creates the first left label to specify what should be placed in the text box
the the right of the label. The rest below does the same.-->
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName">
<span id="firstname_error">*</span><br>
<label for="orderNumber">Order Number:</label>
<input type="text" id="orderNumber" name="orderNumber">
<span id="orderNumber_error">*</span><br>
<label for="date_of_order">Date of Order:</label>
<input type="text" id="date_of_order" name="date_of_order">
<span id="date_of_order_error">*</span><br>
<label for="email_address">Email Address:</label>
<input type="text" id="email_address" name="email_address">
<span id="email_address_error">*</span><br>
<label> </label>
<input type="button" id="form_submission" value="Submit this Form">
</fieldset>
</form>
</div>
<div class="clearfix">
</div>
<IMG class="Wrap1" SRC="cookie.gif" alt="cookie">
<IMG class="Wrap2" SRC="cookie.gif" alt="cookie2">
</body>
</html>
There were a great many things wrong with your code, but the biggest was your validation tests, that each followed the same structure of:
if(FirstName !== "Cherry", "Micheal", "Sandra", "Cookie")
You can't test firstName against a comma-separated list of values. Each one must be tested individually and you must use a compound logical operator between them:
if(FirstName !== "Cherry" && FirstName !== "Micheal" &&
FirstName !== "Sandra" && FirstName !== "Cookie")
You were also using a standard button, rather than a submit button, which can cause all your validation to be bypassed in some situations when the ENTER key is hit. Always use a submit button and validate in the submit event.
Please see my restructured and re-organized code solution for inline comments.
The Stack Overflow snippet environment (below) doesn't work with forms
(because it's sandboxed), but the same code can be run here.
// W3C DOM Event model instead of node event properties:
window.addEventListener("DOMContentLoaded", function() {
// Since we're now using the submit event, we hook into that event:
// Use camelCase for JavaScript identifiers
var form = getElem("cookieForm");
form.addEventListener("submit", validate);
getElem("emailAddress").focus();
// Opening curly braces should appear on the same line as the declaration they open
// Dollar signs are legal identifiers, but usually denote libraries (like JQuery) and
// can be confusing if you are not using those libraries.
function getElem (id) {
return document.getElementById(id);
}
function validate(evt) {
var inputs = document.querySelectorAll(".validate");
// It's better logic to assume false, which avoids "false positives"
var isValid = false;
// Loop through the fields that need validation
for (var i = 0; i < inputs.length; ++i){
var message = ""; // This is the potential error message
// Validate the input according to its id:
switch (inputs[i].id) {
case "firstName" :
// You can't check a single value against a comma-separated list, you have to check
// it against each value you are interested in:
isValid = (inputs[i].value !== "Cherry" && inputs[i].value !== "Micheal" &&
inputs[i].value !== "Sandra" && inputs[i].value !== "Cookie") ? false : true;
message = (!isValid) ? "This person does not exist." : "";
break;
case "orderNumber" :
// Remember, HTML form fields always return strings, not numbers
isValid = (inputs[i].value !== "3134" && inputs[i].value !== "4234" &&
inputs[i].value !== "9234" && inputs[i].value !== "3566") ? false : true;
message = (!isValid) ? "Invalid Order Number." : "";
break;
case "dateOfOrder" :
isValid = (inputs[i].value !=='12-07-23' && inputs[i].value !== '15-04-24' &&
inputs[i].value !== '16-02-01' && inputs[i].value !== '14-01-12') ? false : true;
message = (!isValid) ? "Date doesn't exist in system" : "";
break;
case "emailAddress" :
isValid = (inputs[i].value != "cherryjackson#gmail.com" &&
inputs[i].value !== "michealroberts#yahoo.com" &&
inputs[i].value !== "sandrabell#hotmail.com" &&
inputs[i].value !== "cookiedanny#outlook.com") ? false : true;
message = (!isValid) ? "The email doesn't exist" : "";
break;
}
// Update the UI with the correct message:
inputs[i].nextElementSibling.textContent = message;
}
if(!isValid) {
// cancel the submission if we're invalid
evt.preventDefault(); // Cancel the form's submission
evt.stopPropagation(); // Don't bubble the event
}
}
});
body{
background-color:#FBFBE8;
}
/* Tells HTML5 to find the font-type-face that my OS has and then use that for heading 1
and also centers the first heading */
h1{
font-family:Arial, Helvetica, sans-serif;
text-align:center;
}
/* Tells HTML5 to use any of the font-types for my first paragraph in HTML source file
if one is not available. Also clears some white space
from the left margin of the paragraph and finally tells it to give that paragraph
a size of 20 pixels. */
p {
font-family:Arial, Helvetica, sans-serif;
padding: 20px;
font-size:20px;
}
label{
float: left;
width: 11em;
text-align: right;
font-family:Arial, Helvetica, sans-serif;
color:#800000;
}
input{
margin-left: 1em;
margin-bottom:.5em;
}
span {
color: red;
}
.field_set_1{
border-color: purple;
border-style: solid;
}
#form_submission{ background-color:black; color:white; }
legend{
font-family:Arial, Helvetica, sans-serif;
color:blue;
}
/* All of the classes are just for positioning and floating the four
same images around the form input information */
.Wrap1{
float:right;
margin:40px;
width:200px;
height:200px;
}
.Wrap2{
float:left;
margin:40px;
width:200px;
height:200px;
}
.clearfix {
clear: both;
}
<form id="cookieForm" name="cookieForm" action="submit form.html" method="get">
<fieldset class="field_set_1">
<!-- Below sets the title of the form-->
    <legend>Customer Order Form Information:</legend>
<!-- Creates the first left label to specify what should be placed in the text box
the the right of the label. The rest below does the same.-->
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName" class="validate">
<span id="firstname_error">*</span><br>
<label for="orderNumber">Order Number:</label>
<input type="text" id="orderNumber" name="orderNumber" class="validate">
<span id="orderNumber_error">*</span><br>
<label for="dateOfOrder">Date of Order:</label>
<input type="text" id="dateOfOrder" name="dateOfOrder" class="validate">
<span id="dateOfOrder_error">*</span><br>
<label for="emailAddress">Email Address:</label>
<input type="text" id="emailAddress" name="emailAddress" class="validate">
<span id="emailAddress_error">*</span><br>
<label> </label>
<!-- Always use a "submit" button to initiate form submission, even
if there will be form validation -->
<input type="submit" id="form_submission" value="Submit this Form">
</fieldset>
</form>

Categories

Resources