JavaScript Inline Validation not Working - javascript

I'm trying Javascript inline form validation for the first time. I borrowed the code from another website and have done everything suggested to get it correct but it's still not working. It's supposed to turn the form box red if info is wrong and print a message underneath the incorrect box and turn it green if the info entered is correct. Please help.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Request Info</title>
<link href="bnb stylesheet.css" rel="stylesheet" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:400,700,800' rel='stylesheet' type='text/css'>
<style type="text/css">
.sidebar1 {
float: right;
width: 180px;
background-color: #9CBEEF;
padding-bottom: 10px;
}
</style>
<script>
//Script validation coding borrowed from Philip Brown on Culttt.com
//culttt.com/2012/08/08/really-simple-inline-javascript-validation/
//Validation
function validateName(x){
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if(re.test(document.getElementById(x).value)){
// Style green
document.getElementById(x).style.background ='#ccffcc';
// Hide error prompt
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
// Style red
document.getElementById(x).style.background ='#e35152';
// Show error prompt
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
function validateName(lname){
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if(re.test(document.getElementById(lname).value)){
// Style green
document.getElementById(lname).style.background ='#ccffcc';
// Hide error prompt
document.getElementById(lname + 'Error').style.display = "none";
return true;
}else{
// Style red
document.getElementById(lname).style.background ='#e35152';
// Show error prompt
document.getElementById(lname + 'Error').style.display = "block";
return false;
}
}
// Validate email
function validateEmail(email){
var re = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(re.test(document.getElementById(email).value)){
document.getElementById('email').style.background ='#ccffcc';
document.getElementById('emailError').style.display = "none";
return true;
}else{
document.getElementById('email').style.background ='#e35152';
return false;
}
}
//Validate phone
function validatePhone(phone){
// Validation rule
var re = /[0-9-']$/;
// Check input
if(re.test(document.getElementById(phone).value)){
// Style green
document.getElementById(phone).style.background ='#ccffcc';
//Validate Comments
function validateComment(x){
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if(re.test(document.getElementById(comment).value)){
// Style green
document.getElementById(comment).style.background ='#ccffcc';
// Hide error prompt
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
// Style red
document.getElementById(x).style.background ='#e35152';
// Show error prompt
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
// Hide error prompt
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
// Style red
document.getElementById(x).style.background ='#e35152';
// Show error prompt
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
// Validate Select boxes
function validateCheckbox(terms){
if(document.getElementById(terms).checked){
return true;
}
return false;
}
function validateForm(){
// Set error catcher
var error = 0;
// Check name
if(!validateName('name')){
document.getElementById('nameError').style.display = "block";
error++;
}
//Validate last name
if(!validateName('lname')){
document.getElementById('nameError').style.display = "block";
error++;
}
//Validate phone
if(!validatePhone('phone')){
document.getElementById('phoneError').style.display = "block";
error++;
}
// Validate email
if(!validateEmail(document.getElementById('email').value)){
document.getElementById('emailError').style.display = "block";
error++;
}
//Validate message
if(!validateComment('comment')){
document.getElementById('commentError').style.display = "block";
error++;
}
//Validate Checkbox
if(!validateCheckbox('terms')){
document.getElementById('termsError').style.display = "block";
error++;
}
// Don't submit form if there are errors
if(error > 0){
return false;
}
}
</script>
</head>
<body>
<div class="container">
<div class="header"><img src="images/logo 3.png" alt="Insert Logo Here" name="Insert_logo" width="980" height="200" id="Insert_logo" style="background-color: #9cbeef; display:block;" />
</div>
<div id="navcontainer">
<ul id="navlist1">
<li id="active1">Home</li>
<li>Host</li>
<li>Guest</li>
<li>About Us</li>
<li>Request Info</li>
</ul>
</div> </div>
<div class="content">
<div class="content">
<h1>Contact</h1>
<form action="Request Info2.html" onsubmit="return validateForm()" method="post">
<fieldset>
<legend>Required Information</legend>
<table cellpadding="3">
<tr><td><label for="name"><strong>First Name:</strong></label></td><td>
<input type="text" name="name" id="name" maxlength="30" onblur="validateName(name)" placeholder="Johnny"/>
<span id="fnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span></td></tr>
<tr><td><label for="lname"><strong>Last Name:</strong></label></td><td>
<input type="text" name="lname" id="lname" maxlength="30" onblur="validateName(lname)" placeholder="Smith"/>
<span id="lnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span></td></tr>
<tr><td><label for="email"><strong>Email:</strong></label></td><td>
<input type="text" name="email" id="email" maxlength="75" onblur="validateEmail(email)" placeholder="johndoe#email.com"/>
<span id="emailError" style="display: none;">You can must enter a valid email address</span></td></tr>
<tr><td><label for="phone"><strong>Phone:</strong></label></td><td>
<input type="text" name="phone" id="phone" maxlength="11" onblur="validatePhone(phone)" placeholder="303-777-7777"/>
<span id="phoneError" style="display: none;">You can only use numbers</span></td></tr>
<tr><td><strong><label for="comment">Comments:</strong></label>
</td><td>
<textarea input type="text" name="comment" id="comment" textarea rows="10" cols="30"maxlength="500" >
</textarea>
<span class="validateComment" id="commentError" style="display: none;">Please leave us your comments</span></td></tr>
</table>
</fieldset>
<fieldset style="text-align: center" >
<label ="terms"><strong>Terms and Conditions</strong></label><br>
<p>Please read our Privacy Policy before submitting. We will always protect your privacy. You have the ability to change, update or terminate your information on the site at anytime you choose. B-n-B Concierges also reserves the right to remove any person from the site at their discretion. </p>
<br/>
I confirm that I agree with terms & conditions
<input type="checkbox" name="terms" id="accept" value="accept" maxlength="10" onblur="validateCheckbox(terms)" />
<span class="validateError" id="termsError" style="display: none;">You need to accept our terms and conditions</span>
</fieldset>
<fieldset>
<input type="submit" id="submit" name="submit" value="Submit" />
</fieldset>
</form>
</div>
</div>
<div class="footer">
<p><div id="navcontainer">
<ul id="navlist2">
<li id="active2"><a href="Policies.html" >Conditions</a></li>
<li>Privacy</li>
<li>Sign Up</li>
<li>© 2014 Heidi Medina</li>
</ul>
</div>
</div>
</body>
</html>

#user3446663:
The following code works. Note that I have left the form action property empty because you had a space in the name of the form you were referring to (Request Info2.html). You'll want to either put an underscore in that file name so it reads 'Request_Info2.html' or remove the space so it reads 'RequestInfo2.html' in order to have the file name be recognized properly. Here's the code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Request Info</title>
<link href="bnb stylesheet.css" rel="stylesheet" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:400,700,800' rel='stylesheet' type='text/css'>
<style type="text/css">
.sidebar1 {
float: right;
width: 180px;
background-color: #9CBEEF;
padding-bottom: 10px;
}
</style>
<script>
//Script validation coding borrowed from Philip Brown on Culttt.com
//culttt.com/2012/08/08/really-simple-inline-javascript-validation/
// Validate first/last name
function validateName(name){
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if (re.test(document.getElementById(name).value)){
// Style green
document.getElementById(name).style.background ='#ccffcc';
// Hide error prompt
document.getElementById(name + 'Error').style.display = "none";
return true;
} else {
// Style red
document.getElementById(name).style.background ='#e35152';
// Show error prompt
document.getElementById(name + 'Error').style.display = "block";
return false;
}
}
// Validate email
function validateEmail(email){
var re = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (re.test(document.getElementById(email).value)){
document.getElementById(email).style.background ='#ccffcc';
document.getElementById(email + 'Error').style.display = "none";
return true;
} else {
document.getElementById(email).style.background ='#e35152';
document.getElementById(email + 'Error').style.display = "block";
return false;
}
}
//Validate Comments
function validateComment(comment){
var re = /[A-Za-z -']$/;
if (re.test(document.getElementById(comment).value)){
document.getElementById(comment).style.background ='#ccffcc';
document.getElementById(comment + 'Error').style.display = "none";
return true;
} else {
document.getElementById(comment).style.background ='#e35152';
document.getElementById(comment + 'Error').style.display = "block";
return false;
}
}
//Validate phone
function validatePhone(phone){
var re = /[0-9-']$/;
if(re.test(document.getElementById(phone).value)){
document.getElementById(phone).style.background ='#ccffcc';
document.getElementById(phone + 'Error').style.display = "none";
return true;
} else {
document.getElementById(phone).style.background ='#e35152';
document.getElementById(phone + 'Error').style.display = "block";
return false;
}
}
// Validate checkbox
function validateCheckbox(terms){
if(document.getElementById(terms).checked){
document.getElementById(terms + 'Error').style.display = "none";
return true;
} else {
document.getElementById(terms + 'Error').style.display = "block";
return false;
}
}
// Validate Form
function validateForm(){
// Set error catcher
var error = 0;
// Validate first name
if (!validateName('fname')){
document.getElementById('fnameError').style.display = "block";
error++;
}
//Validate last name
if (!validateName('lname')){
document.getElementById('lnameError').style.display = "block";
error++;
}
//Validate phone
if (!validatePhone('phone')){
document.getElementById('phoneError').style.display = "block";
error++;
}
// Validate email
if (!validateEmail('email')){
document.getElementById('emailError').style.display = "block";
error++;
}
//Validate message
if (!validateComment('comment')){
document.getElementById('commentError').style.display = "block";
error++;
}
//Validate checkbox
if (!validateCheckbox('terms')){
document.getElementById('termsError').style.display = "block";
error++;
}
// Don't submit form if there are errors
if (error > 0){
return false;
}
}
</script>
</head>
<body>
<div class="container">
<div class="header">
<a href="Request Info.html">
<img src="images/logo 3.png" alt="Insert Logo Here" name="Insert_logo" width="980" height="200" id="Insert_logo" style="background-color: #9cbeef; display:block;" />
</a>
</div>
<div id="navcontainer">
<ul id="navlist1">
<li id="active1">Home</li>
<li>Host</li>
<li>Guest</li>
<li>About Us</li>
<li>Request Info</li>
</ul>
</div>
</div>
<div class="content">
<h1>Contact</h1>
<form action="" onsubmit="return validateForm()" method="post">
<fieldset>
<legend>Required Information</legend>
<table cellpadding="3">
<tr><td><label for="name"><strong>First Name:</strong></label></td><td>
<input type="text" name="fname" id="fname" maxlength="30" onblur="validateName(name)" placeholder="Johnny"/>
<span id="fnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span></td></tr>
<tr><td><label for="lname"><strong>Last Name:</strong></label></td><td>
<input type="text" name="lname" id="lname" maxlength="30" onblur="validateName(name)" placeholder="Smith"/>
<span id="lnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span></td></tr>
<tr><td><label for="email"><strong>Email:</strong></label></td><td>
<input type="text" name="email" id="email" maxlength="75" onblur="validateEmail(name)" placeholder="johndoe#email.com"/>
<span id="emailError" style="display: none;">You can must enter a valid email address</span></td></tr>
<tr><td><label for="phone"><strong>Phone:</strong></label></td><td>
<input type="text" name="phone" id="phone" maxlength="11" onblur="validatePhone(name)" placeholder="303-777-7777"/>
<span id="phoneError" style="display: none;">You can only use numbers</span></td></tr>
<tr><td><strong><label for="comment">Comments:</strong></label></td><td>
<textarea input type="text" name="comment" id="comment" textarea rows="10" cols="30"maxlength="500" onblur="validateComment(name)" ></textarea>
<span class="validateComment" id="commentError" style="display: none;">Please leave us your comments</span></td></tr>
</table>
</fieldset>
<fieldset style="text-align: center" >
<label ="terms"><strong>Terms and Conditions</strong></label><br>
<p>Please read our Privacy Policy before submitting. We will always protect your privacy.
You have the ability to change, update or terminate your information on the site at anytime you choose. B-n-B
Concierges also reserves the right to remove any person from the site at their discretion.</p><br/>
I confirm that I agree with terms & conditions
<input type="checkbox" name="terms" id="terms" value="accept" maxlength="10" onblur="validateCheckbox(name)" />
<span class="validateError" id="termsError" style="display: none;">You need to accept our terms and conditions</span>
</fieldset>
<fieldset>
<input type="submit" id="submit" name="submit" value="Submit" />
</fieldset>
</form>
</div>
<div class="footer">
<div id="navcontainer">
<ul id="navlist2">
<li id="active2"><a href="Policies.html" >Conditions</a></li>
<li>Privacy</li>
<li>Sign Up</li>
<li>© 2014 Heidi Medina</li>
</ul>
</div>
</div>
</body>
</html>

I do not believe this warrants an answer, but I do not have enough reputation to comment as of yet.
Consider using HTML5 patterns if possible.
Examples:
http://html5pattern.com/Names
Polyfill:
https://github.com/ryanseddon/H5F
Most of the time simply specifying the input type is enough (phone, email)
<input type="email" name="" value="" required />
You can fine-tune the validation with the pattern attribute
<input type="text" pattern="[a-zA-Z0-9]+">

There are few minor issues in the code.
ID values are wrongly provided in your JS code
Eg: you have fnameError as ID to display error in firstname.
<span id="fnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span>
Whereas in the Javascript, you have used just nameError
document.getElementById('nameError').style.display = "block";
Similar kind of spelling issue is there in lastname also.. fix if there is anymore reference issues because of spelling differences, then you are good to go.

Related

What is the equivalent of "form-group has-error" in Boostrap 4?

I am trying to make form. When we send information with errors, then should be color red where we entered wrong data and color green where we entered the correct data.
My .js file:
function checkForm()
{
var error=false;
var contactName = document.getElementById("contactName");
var contactLastName = document.getElementById("contactLastName");
var contactEmail = document.getElementById("contactEmail");
var contactInfo = document.getElementById("contactInfo");
if (contactName.value == "")
{
document.getElementById('errorName').className='alert alertdanger';
error=true;
}
if (contactLastName.value == "")
{
document.getElementById('errorLastName').className='alert alertdanger';
error=true;
}
if(contactInfo.value == "")
{
document.getElementById('errorInfo').className='alert alertdanger';
error = true;
}
else
{
var info = contactInfo.value;
if(info.length >= 250)
{
document.getElementById('errorInfoLength').className='alert alertdanger';
error=true;
}
}
if(contactEmail.value == "")
{
document.getElementById('errorMail').className='alert alertdanger';
error=true;
}
else
{
var email = contactEmail.value;
var regex = /^[a-zA-Z0-9._-]+#([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
if(regex.test(email)==false)
{
document.getElementById('errorMailCorrect').innerHTML='Bad format!';
document.getElementById('errorMailCorrect').className='alert alertdanger';
error=true;
}
}
if (!error)
return true;
else
{
return false;
}
}
Form:
<form action="index.html#kontakt" method="post" onsubmit="return checkForm();">
<fieldset>
<div class="form-group" id="error1">
<p id="errorName" class="d-none">Add name!</p>
<label for="contactName">Imię</label>
<input type="text" id="contactName"/>
</div>
<div class="form-group" id="error2">
<p id="errorLastName" class="d-none">Add last name!</p>
<label for="contactLastName">Nazwisko</label>
<input type="text" id="contactLastName"/>
</div>
<div class="form-group" id="error3">
<p id="errorMail" class="d-none">Add email!</p>
<p id="errorMailCorrect" class="d-none">Wrong email!</p>
<label for="contactEmail">Email</label>
<input type="text" id="contactEmail" />
</div>
<div class="form-group" id="error4">
<p id="errorInfo" class="d-none">Add info!</p>
<p id="errorInfoLength" class="d-none">Limit is 250 chars!</p>
<label for="contactInfo">Informacja</label>
<input type="text" id="contactInfo" />
</div>
<input type="submit" value="Submit" />
</fieldset>
</form>
In bootrap 3.4.1 I could simply add to my .js file:
document.getElementById("error1").className="form-group has-error";
What is the equivalent of "form-group has-error" in Boostrap 4?
Also another question. What do you need to do to make the fields on the form validate the details you have entered immediately? Not after we submitted them.
This is explained in the Bootstrap 4 documentation. You can:
Use the :valid and :invalid CSS pseudo-classes. They only work if the form has the class .was-validated.
Or use the .is-valid and is-invalid CSS classes.
Validating before submitting can be done using standard HTML attributes such as required, pattern, etc.. If that does not cover your requirements, you can do it yourself with JavaScript. But that is a whole other topic and it is probably best to use some library or framework for that.

Inserting regular expression for verifying URL address and email address

I need to insert a regular expression to verify the input for URL and email is valid, so where would this go in the code to make it work without messing with anything else? I need to know exactly where it would go and how it would look.
window.onload = function() {
document.getElementById('ifBusiness').style.display = 'none';
}
function BusinessorResidence() {
var is_business = document.getElementById('businessCheck').checked;
if (is_business) {
document.getElementById('ifBusiness').style.display = 'block';
document.getElementById('ifResidence').style.display = 'none';
} else {
document.getElementById('ifBusiness').style.display = 'none';
document.getElementById('ifResidence').style.display = 'block';
}
}
function validateForm() {
var is_business = document.getElementById('businessCheck').checked;
var address = document.forms["myForm"]["address"];
var bname = document.forms["myForm"]["bname"];
var url = document.forms["myForm"]["url"];
var tax = document.forms["myForm"]["tax"];
var rname = document.forms["myForm"]["rname"];
var email = document.forms["myForm"]["email"];
// Address always has to be checked
if (address.value == "") {
alert("Please enter an address.");
address.focus();
return false;
}
// Check the bname, tax and url if a business is selected
if (is_business) {
if (bname.value == "") {
alert("Please enter a business name.");
// focus() is a method, not a property, so you need to call this function to actually focus the text input.
bname.focus();
return false;
}
if (tax.value == "") {
alert("Please enter a business tax ID.");
tax.focus();
return false;
}
if (url.value == "") {
alert("Please enter a business URL.");
url.focus();
return false;
}
}
// Else check the rname and the email
else {
if (rname.value == "") {
alert("Please enter a residence name.");
rname.focus();
return false;
}
if (email.value == "") {
alert("Please enter an email address.");
email.focus();
return false;
}
}
// Open the popup window.
// _blank refers to it being a new window
// SELU is the name we'll use for the window.
// The last string is the options we need.
var popup = window.open('', 'SELU', 'toolbar=0,scrollbars=0,location=0,statusb ar=0,menubar=0,resizable=0,width=400,height=400,left=312,top=234');
// Set the form target to the name of the newly created popup.
var form = document.querySelector('form[name="myForm"]');
form.setAttribute('target', 'SELU');
return true;
}
head {
text-align: center;
}
body {
text-align: center;
}
.bold {
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<title>Javascript Assignment</title>
<!-- the titles should be inside the title, not inside the <head> tag -->
<h1>Fill the form below</h1>
<!-- center tag is deprecated and should be replaced by CSS -->
</head>
<body>
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<p>
<b>Address: </b>
<input type="text" name="address">
</p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence
<br>
<div id="ifBusiness" style="display:none">
<!-- <b> tag is deprecated. should be done with CSS -->
<span class="bold">Business Name:</span>
<input type="text" id="name" name="bname">
<br>
<span class="bold">Business Website URL:</span>
<input type="text" id="url" name="url">
<br>
<span class="bold">Business Tax ID: </span>
<input type="text" id="tax" name="tax">
</div>
<div id="ifResidence" style="display:none">
<b>Name: </b>
<input type="text" id="name" name="rname">
<br>
<b>Email: </b>
<input type="text" id="email" name="email">
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>
<hr>
<hr>
</body>
</html>
To validate whether or not a user is inputting an url/email, simply change your input type to "url" or "email" and it will be validated for you.
Like so:
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<p>
<b>Address: </b>
<input type="text" name="address">
</p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence
<br>
<div id="ifBusiness" style="display:none">
<!-- <b> tag is deprecated. should be done with CSS -->
<span class="bold">Business Name:</span>
<input type="text" id="name" name="bname">
<br>
<span class="bold">Business Website URL:</span>
<input type="url" id="url" name="url">
<br>
<span class="bold">Business Tax ID: </span>
<input type="text" id="tax" name="tax">
</div>
<div id="ifResidence" style="display:none">
<b>Name: </b>
<input type="text" id="name" name="rname">
<br>
<b>Email: </b>
<input type="email" id="email" name="email">
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>

Javascript Error message flashes for only a second [duplicate]

This question already has answers here:
What is the meaning of onsubmit="return false"? (JavaScript, jQuery)
(4 answers)
Closed 5 years ago.
I have this HTML project that validates an empty form. The error is being displayed on the side of the inputs but only flashes for a second. I just want the error of the messages to be displayed once
This is my HTML code with the necessary links:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript - JQuery </title>
<link rel="stylesheet" type="text/css" href="contactform.css">
</head>
<body>
<h1 id="pageheading">Zedland Health Authority</h1>
<h2 class="sectionheading">Contact Form</h2>
<form id="register">
<fieldset id="controls">
<div>
<label class="formlabel" for="fname">First Name: </label>
<input id="fname" type="text" size="30" placeholder="First name"
autofocus>
<p id="fname-error" class="error" style="display:none; color:red;">*
You must enter a first name.</p>
</div>
<div>
<label class="formlabel"for="lname">Last Name: </label>
<input id="lname" type="text" size="30">
<p id="lname-error" class="error" style="display:none; color:red;">*
You must enter a Last name.</p>
</div>
<div>
<label class="formlabel" for="title">Title: </label>
<select id="title">
<option value="Mr">Mr.</option>
<option value="Ms">Ms.</option>
<option value="Mrs">Mrs.</option>
<option value="Miss">Miss.</option>
<option value="Master">Master.</option>
</select>
</div>
<div>
<label class="formlabel" for="heathauthoritynumber"><span>
<img src="tooltip.png" id="qmark" alt="Hint"></span>
Health Authority Number:
</label>
<input id="healthauthoritynumber" type="text" size="10">
<p id="hn-error" class="error" style="display:none; color:red;">*You
must enter a Health Authority Number eg('ZHA345742)</p>
<div class="tooltip" id="ttip">If you do not know your ZHA number
,please contact your GP</div>
</div>
<div>
<label class="formlabel" for="email">Email: </label>
<input id="email" type="text" size="40">
<p id="email-error" class="error" style="display:none; color:red;">You
must enter email</p>
</div>
<div>
<label class="formlabel" for="telephone">Telephone Number: </label>
<input id="telephone" type="text" size="40">
<p id="tele-error" class="error" style="display:none; color:red;">You
must enter a telephone</p>
</div>
<div class="formlabel">
<input id="submit-button" type="submit" value="Submit" >
</div>
</fieldset>
</form>
<script src="contactform.js"></script>
</body>
</html>
This is my Javascript
function onSubmit(){
console.log("ive been submitted");
checkEmpty(document.getElementById('fname'),document.getElementById("fname-error"));
checkEmpty(document.getElementById('lname'),document.getElementById("lname-error"));
checkEmpty(document.getElementById('healthauthoritynumber'),document.getElementById("hn-error"));
checkEmpty(document.getElementById('email'),document.getElementById("email-error"));
checkEmpty(document.getElementById('telephone'),document.getElementById("tele-error"));
//checkValidHealthID(document.getElementById('healthauthoritynumber'),document.getElementById("hn-error"));
}
// Read about regular expressions using: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
// and http://stackoverflow.com/questions/25155970/validating-uk-phone-number-regex-c
function checkValidHealthID(inputID, errorID){
var re = new RegExp('/ZHA\d{6}$/');
if((inputID.value)!== re){
errorID.style.display = "inline";
}else
{
errorID.style.display = "none";
}
}
function checkEmpty(inputID, errorID){
//Default behaviour at for FORM is to reload the HTML page
//e.preventDefault();
console.log("checking empty");
if((inputID.value === "") || (inputID.value.length === 0)){
console.log("empty!!");
errorID.style.display = "inline";
}
else
{
errorID.style.display = "none";
}
}
function textHint(txtElem, defaultText) {
txtElem.value = defaultText;
txtElem.style.color = "#A8A8A8";
txtElem.style.fontStyle = "italic";
txtElem.onfocus = function() {
if (this.value === defaultText) {
this.value = "";
this.style.color = "#000";
this.style.fontStyle = "normal";
}
}
txtElem.onblur = function() {
if (this.value === "") {
this.value = defaultText;
this.style.color = "#A8A8A8";
this.style.fontStyle = "italic";
}
}
}
function textHints() {
//textHint(document.getElementById("firstName"), "Enter your first name");
textHint(document.getElementById('lname'), "Enter your last name");
textHint(document.getElementById('healthauthoritynumber'), "for eg
,ZHA346783");
textHint(document.getElementById('email'), "Enter your email");
textHint(document.getElementById('telephone'), "Enter your telephone
number");
}
function switchToolTip() {
document.getElementById('qmark').onmouseover = function() {
var toolTip = document.getElementById('ttip');
toolTip.style.display='block';
}
document.getElementById('qmark').onmouseout = function() {
var toolTip = document.getElementById('ttip');
toolTip.style.display='none';
}
}
//windows.onload=textHints();
//windows.onload=switchToolTip();
//window.onload=init;
document.getElementById("submit-button").onclick = onSubmit;
Your form is getting submitted which results in page reload. That's why you see the message flashing for a while. I saw the commented line in your JavaScript
//Default behaviour at for FORM is to reload the HTML page
//e.preventDefault();
You should get uncomment e.preventDefault().
Grab the click event as function onSubmit(event) and pass the event to checkEmpty.

prevent form from submitting not working, JavaScript

Hello and thank you for your time.
I have a form with the id payment and a submit button, but there seems to be a mistake in my JavaScript, as I only get the alert message but the page still submits if I input a wrong name like a row of hash symbols #######. the code below is exactly how it is in my file.
// form validation, makes sure that the user inputs the correct data types.
function validateinput(event){
var email = document.getElementById('email').value;
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
var message = document.getElementById('message').value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
var firstnameFilter = /^([" "a-zA-Z.-])+$/;
var lastnameFilter = /^([" "a-zA-Z.-])+$/;
var messageFilter = /^([" "a-zA-Z0-9_.-])+$/;
if (!emailFilter.test(email)) {
alert('!Enter a email. Or enter a valid email address.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!firstnameFilter.test(firstname)) {
alert('!Enter a first name. Or enter a valid name.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!lastnameFilter.test(lastname)) {
alert('!Enter a last name. Or enter a name., only letters');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!messageFilter.test(message)) {
alert('!Enter a message.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
alert ('Your order was submited')
}
document.getElementById('payment').addEventListener("submit", validateinput)
have also tried other methods thought they do not seem too work on this page but works on others ?
Like changing the var names and id,s in this one i am using on my contact page
function validateinput(event){
var address1 = document.getElementById('address1').value;
var postcode = document.getElementById('postcode').value;
var address1Filter = /^([" "a-zA-Z0-9_.-])+$/;
var postcodeFilter = /^([" "a-zA-Z0-9_.-])+$/;
var formValid = true;
if (!address1Filter.test(address1)) {
alert('!Enter an address. Or enter a valid address., only letters and numbers');
formValid = false;
event.preventDefault();
return false;
}
if (!postcodeFilter.test(postcode)) {
alert('!Enter a postcode. Or enter a valid postcode., only letters and numbers');
formValid = false;
event.preventDefault();
return false;
}
alert ('Your order was submited')
}
document.getElementById('payment').addEventListener("submit", validateinput)
So what am I doing wrong ?
the html
<!doctype html>
<!-- name: Edwin martin -date: 30/11/2015 -task: a form with split up inputs using the
<fieldset> & <legend> tags -->
<html lang="en">
<head>
<title>contact</title>
<script type="text/javascript" src="scripts/contact2.js"> </script>
<!-- ensures the document is using the correct char set -->
<meta charset="utf-8">
<meta name="description" content="contact page">
<link rel="icon" href="images/fav.png" type="image/png"/>
<!--
The below section looks like a comment, but it's a conditional include statement.
It's ignored by all browsers except IE9. html5shiv is a library that fixes some HTML5
IE bugs.
-->
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- pulls in the styles sheet -->
<link rel="stylesheet" href="styles/indexstyles.css">
</head>
<body onload="main()">
<!-- start of the form, id form sets the position, size, border style and color -->
<div id="form2">
<!-- sets the link position, list and text style of the header, id head color sets the background color for the division around the header -->
<div id="head">
<header id="headcolor">
<div id="toplinks">
<ul>
<li class="tl"> <input type="button" class="topbutton" name="b1" value="Index" onclick="location.href='index.html'"> </li>
<li class="tl"> <input type="button" class="topbutton" name="b1" value="order" onclick="location.href='order.html'"> </li>
</ul>
</div> <br>
<br>
</header>
<h1 id="title"> Contact </h1>
<p> southampton solent pizzas: southampton solent university branch. E Park Terrace, Southampton, Hampshire SO14 0YN </p>
</div>
<div id="map"> </div>
<!-- id payment sets the input boxs background color , position and border for invaild - vaild -->
<form id="payment">
<!-- Contact Information section -->
<fieldset>
<legend> Personal Information </legend>
<p> <label> First Name(*): </label> <input type="text" name="first_name" id="firstname" placeholder="enter a first name" class="add1"></p>
<p> <label> Last Name(*): </label> <input type="text" name="last_name" id="lastname" placeholder="enter a last name" class="add1"></p>
<p> <label> Email(*): </label> <input type="text" name="email" id="email" placeholder="enter a email" class="add1"></p>
<p> <label>Phone Number: </label> <input type="text" name="phone" id="phone"></p>
<p> <label> message(*): </label> <input type="text" name="message" id="message" placeholder="enter your message" class="add1"></p>
</fieldset>
<!-- Submit button -->
<input type="submit" class="submit_button">
<input type="reset" class="reset_button">
</form>
</div>
<script type="text/javascript" src="scripts/contact.js"> </script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
</body>
</html>
i also have another JS script as you can see from the two different links. but even if i remove that link - code there form still submits with the wrong input, as this code just reads a empty input
//onload callback function
function main() {
console.log("in main function");
var myForm = document.getElementById("payment");
myForm.addEventListener("submit",validateForm);
}
//validate callback function
function validateForm(event) {
var formValid = true;
var myForm = document.getElementById("payment");
if (myForm.first_name.value == "") {
formValid = false;
//display error message
document.getElementById("firstname").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.last_name.value == "") {
formValid = false;
//display error message
document.getElementById("lastname").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.email.value == "") {
formValid = false;
//display error message
document.getElementById("email").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.message.value == "") {
formValid = false;
//display error message
document.getElementById("message").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
}
document.getElementById('payment').addEventListener("submit", validateinput), the problem is that you want to pass an argument to the validateinput method, but you can't do it that way, to pass arguments to a callback method reference, you should wrap it in an anonymous function like this.
document.getElementById('payment').addEventListener("submit", function(event) {
validateinput(event);
});
I think you're over complicating your Javascript. If you change your submit to call the function directly you'll have an easier time handling the negative states.
<input type="submit" onclick="return validateinput();" class="submit_button">
You'll need to modify the validateinput function slightly since you won't have event being passed in anymore.

javascript form validation for empty field and wrong input

this program runs correctly.. my task is, when name field left empty then (please enter your name )this error will be generated and when i type wrong input(like numbers)then (only alphabets and white space are allowed)this error message has to be generate. how can i do this.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Validation tutorial</title>
<script>
function validateName(x){
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if(re.test(document.getElementById(x).value)){
// Style green
document.getElementById(x).style.borderColor ='#3BFF3B';
// Hide error prompt
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
// Style red
document.getElementById(x).style.borderColor ='#FF0000';
// Show error prompt
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
// Validate email
function validateEmail(email){
var re = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(re.test(email)){
document.getElementById('email').style.borderColor ='#3BFF3B';
document.getElementById('emailError').style.display = "none";
return true;
}else{
document.getElementById('email').style.borderColor ='#FF0000';
return false;
}
}
// Validate Select boxes
function validateSelect(x){
if(document.getElementById(x).selectedIndex !== 0){
document.getElementById(x).style.borderColor ='#3BFF3B';
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
document.getElementById(x).style.borderColor ='#FF0000';
return false;
}
}
function validateRadio(x){
if(document.getElementById(x).checked){
return true;
}else{
return false;
}
}
function validateCheckbox(x){
if(document.getElementById(x).checked){
return true;
}
return false;
}
function validateForm(){
// Set error catcher
var error = 0;
// Check name
if(!validateName('name')){
document.getElementById('nameError').style.display = "block";
error++;
}
// Validate email
if(!validateEmail(document.getElementById('email').value)){
document.getElementById('emailError').style.display = "block";
error++;
}
// Validate animal dropdown box
if(!validateSelect('subject')){
document.getElementById('subjectError').style.display = "block";
error++;
}
// Validate Radio
if(validateRadio('male')){
}else if(validateRadio('female')){
}else{
document.getElementById('genderError').style.display = "block";
error++;
}
// Don't submit form if there are errors
if(error > 0){
return false;
}
}
</script>
</head>
<body>
<form action="" onsubmit="return validateForm()">
<label for="name">Name</label>
<input type="text" name="name" id="name" onblur="validateName(name)" />
<span id="nameError" style="display: none;">only alphabates and white space are allowed</span>
<br><br>
<label for="email">Email</label>
<input type="text" name="email" id="email" onblur="validateEmail(value)" />
<span id="emailError" style="display: none;">You must enter a valid email address</span>
<br><br>
<label for="hand">Gender</label>
<ul>
<li>
<input type="radio" name="gender" id="male" value="male" onblur="validateRadio(id)" />
<label for="left">male</label>
</li>
<li>
<input type="radio" name="gender" id="female" value="female" onblur="validateRadio(id)" />
<label for="right">female</label>
</li>
</ul>
<span class="validateError" id="genderError" style="display: none;">Please select gender</span>
<br><br>
<label for="subject">Favourite Subject</label>
<select name="subject" id="subject" onblur="validateSelect(name)">
<option value="">SUBJECTS</option>
<option value="php">PHP</option>
<option value="java">JAVA</option>
<option value="sql">SQL</option>
</select>
<span class="validateError" id="subjectError" style="display: none;">You must select your favourite subject</span>
<br><br>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Validation tutorial</title>
<script>
function validateName(x){
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if(re.test(document.getElementById(x).value)){
// Style green
document.getElementById(x).style.borderColor ='#3BFF3B';
// Hide error prompt
document.getElementById(x + 'Error').style.display = "none";
return true;
}else if(document.getElementById(x).value === ''){
//This is for an empty string or if name was not entered.
// Style red
document.getElementById(x).style.borderColor ='#FF0000';
// Show error prompt
document.getElementById(x + 'Error2').style.display = "block";
return false;
}else{
// Style red
document.getElementById(x).style.borderColor ='#FF0000';
// Show error prompt
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
// Validate email
function validateEmail(email){
var re = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(re.test(email)){
document.getElementById('email').style.borderColor ='#3BFF3B';
document.getElementById('emailError').style.display = "none";
return true;
}else{
document.getElementById('email').style.borderColor ='#FF0000';
return false;
}
}
// Validate Select boxes
function validateSelect(x){
if(document.getElementById(x).selectedIndex !== 0){
document.getElementById(x).style.borderColor ='#3BFF3B';
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
document.getElementById(x).style.borderColor ='#FF0000';
return false;
}
}
function validateRadio(x){
if(document.getElementById(x).checked){
return true;
}else{
return false;
}
}
function validateCheckbox(x){
if(document.getElementById(x).checked){
return true;
}
return false;
}
function validateForm(){
// Set error catcher
var error = 0;
// Check name
if(!validateName('name')){
document.getElementById('nameError').style.display = "block";
error++;
}
// Validate email
if(!validateEmail(document.getElementById('email').value)){
document.getElementById('emailError').style.display = "block";
error++;
}
// Validate animal dropdown box
if(!validateSelect('subject')){
document.getElementById('subjectError').style.display = "block";
error++;
}
// Validate Radio
if(validateRadio('male')){
}else if(validateRadio('female')){
}else{
document.getElementById('genderError').style.display = "block";
error++;
}
// Don't submit form if there are errors
if(error > 0){
return false;
}
}
</script>
</head>
<body>
<form action="" onsubmit="return validateForm()">
<label for="name">Name</label>
<input type="text" name="name" id="name" onblur="validateName(name)" />
<span id="nameError" style="display: none;">only alphabates and white space are allowed</span>
<span id="nameError2" style="display: none;">please enter a name</span>
<br><br>
<label for="email">Email</label>
<input type="text" name="email" id="email" onblur="validateEmail(value)" />
<span id="emailError" style="display: none;">You must enter a valid email address</span>
<br><br>
<label for="hand">Gender</label>
<ul>
<li>
<input type="radio" name="gender" id="male" value="male" onblur="validateRadio(id)" />
<label for="left">male</label>
</li>
<li>
<input type="radio" name="gender" id="female" value="female" onblur="validateRadio(id)" />
<label for="right">female</label>
</li>
</ul>
<span class="validateError" id="genderError" style="display: none;">Please select gender</span>
<br><br>
<label for="subject">Favourite Subject</label>
<select name="subject" id="subject" onblur="validateSelect(name)">
<option value="">SUBJECTS</option>
<option value="php">PHP</option>
<option value="java">JAVA</option>
<option value="sql">SQL</option>
</select>
<span class="validateError" id="subjectError" style="display: none;">You must select your favourite subject</span>
<br><br>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</body>
</html>
There are much better ways to do this. This is not an elegant way. I see this code is from an example or tutorial. Please check other tutorials on this subject, as this is just a quick way of implementing what you want.

Categories

Resources