for some reason this does not work, its so simple and i see a million examples of this working. This is basic validation just to see if they did not click in one of the examples to not submit the form. I have validation for the first, last name and email. The text area i was going to validate using this function.
***********************EDITED************************
***************So i am adding more of my code so yall can see the issue better. NOTE: Some code in script and other places have been modified. I will add a CODECHANGED so you know its a intentional mistake. Also, the css is huge and mostly unnecessary im sure you can guess whats going on here.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title Undetermined</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/hammerFavicon.ico" type="image/gif">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" CODECHANGED >
<link rel="stylesheet" href = "css/custom/siteStyle.css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" CODECHANGED ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" CODECHANGED "></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" CODECHANGED ></script>
<script src="js/main.js"></script>
</head>
<body>
<!-- Header include -------------------------------------------------------------------------------------- -->
<?php include("includes/header.php"); ?>
<!-- Navigation include ---------------------------------------------------------------------------------- -->
<?php include("includes/navigation.php"); ?>
<!-- Main Content section -------------------------------------------------------------------------------- -->
<main role="main" class="container">
</div>
<div class="jumbotron">
<!-- Paragraph for text if needed ---------------------------------------------------------------- -->
<p class="lead">
<h2>Ask Us A Question</h2>
<br />
<!-- Question submission form ---------------------------------------------------------------- -->
<form id="myForm" action="" onsubmit="return validForm()">
<div class="form-group">
<div class="col">
<label for="fN">First Name</label>
<input type="text" onblur="validateName(fN)" class="form-control" placeholder="First Name" id="fN">
</div>
</div>
<!--Last Name -------------->
<div class="form-group">
<div class="col">
<label for="lN">Last Name</label>
<input type="text" onblur="validateName(lN)" class="form-control" placeholder="Last Name" id="lN">
</div>
</div>
<!-- Email -->
<div class="form-group">
<div class="col">
<label for="eMail">Email</label>
<input type="email" onblur="validateEmail(eMail)" class="form-control" placeholder="Email" id="eMail">
</div>
</div>
<br/>
<!--Question Topic----------------------------------------------------------------------->
<h5>Select Question Category</h5>
<div class="form-group form-control">
<select id="qCategory" required>
<option selected>Select Category</option>
<option></option>
<option></option>
<option></option>
<option></option>
</select>
<br>
<br>
<!-- Question Details text field ------------------------------------------------------ -->
<h5>Enter your question:</h5>
<div class="form-group">
<textarea id="txtArea" class="form-control" rows = "6" cols = "65"></textarea>
</div>
<br>
</div>
<br />
<div class="form-group">
<div>
<h5 id="formError">Please fill in entire form</h5>
<button onclick="return validForm()" type="submit" class="button button-block" id="cTModal">Create Ticket</button>
</div>
</form>
</p>
</div>
</main>
<!-- Footer include -------------------------------------------------------------------------------------- -->
<?php include("includes/footer.php"); ?>
</body>
</html>
--------BEGIN JAVASCRIPT-------------------------------------
//Checks if user has pressed update without entering fields
function validateName(x){
var re = /[A-Za-z]$/;
if (x.value == ""){
x.style.background = '#e35152';
x.style.color = 'white';
fN.value = "Please enter your first name";
lN.value = "Please enter your last name";
return false;
} else {
if (!re.test(x.value)){
x.style.background = '#e35152';
x.style.color = 'white';
x.value = "Please use only characters";
return false;
} else {
x.style.background = 'white';
x.style.color = 'black';
return true;
}
}
}
function validateEmail(x){
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (x.value == ""){
x.style.background = '#e35152';
x.style.color = 'white';
x.value = "Please fill in email";
return false;
} else {
if (!re.test(x.value)){
x.style.background = '#e35152';
x.style.color = 'white';
x.value = "You must enter a valid email";
return false;
} else {
x.style.background = 'white';
x.style.color = 'black';
return true;
}
}
}
function validForm(){
var eMail = document.getElementById('eMail').value;
var lastName = document.getElementById('fN').value;
var firstName = document.getElementById('lN').value;
var formError = document.getElementById('formError');
if(firstName == ''){
formError.style.display = 'block';
return false;
} else if (lastName == ''){
formError.style.display = 'block';
return false;
} else if (eMail == ''){
formError.style.display = 'block';
return false;
} else {
formError.hide();
return true;
}
}
The first thing I notice is that your formError variable is the value of the formError element not the element itself. So your call to .style will fail.
Related
currently, im working on a form validation project with with four fields. Im using regular expressions in order to validate the input but looks like something is wrong because every time that I hit the submit button the form dosent validate the data that is just entered.
Can anyone Help me out?
Heres my html & javascript code.
function validate () {
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
const phone = document.getElementById('phone').value;
const regEmail = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const regpass = /^(?=.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{10,16}$/;
const regphone =/^ (0|\+98)?([ ]|-|[()]){0,2}9[1|2|3|4]([ ]|-|[()]){0,2}(?:[0-9]([ ]|-|[()]){0,2}){8}/;
const resultemail = regEmail.test('email');
const resultpass = regpass.test('password');
const resultphone = regphone.test('phone');
//conditions
if(resultemail == false || resultemail == "") {
document.getElementsByClassName('erroremail').innerHtml = "لطفا ایمیل را با فرمت صحیح وارد کنید";
return false;
} else {
document.getElementsByClassName('validemail').innerHtml= "ایمیل صحیح است";
}
if(resultpass == false || resultpass == "") {
document.getElementsByClassName('errorpass').innerHtml = "لطفا پسورد را با فرمت صحیح وارد کنید";
return false;
} else {
document.getElementsByClassName('erroremail').innerHtml = "پسورد صحیح است";
}
if(resultphone == false || resultphone == "") {
document.getElementsByClassName('errorphone').innerHtml = "شماره تلفن اجباری است";
return false;
} else {
document.getElementsByClassName('validphone').innerHtml = "شماره تلفن صحیح است";
}
return true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<title>Document</title>
</head>
<body>
<form action="submit" method="get" onclick="validate()">
<div>
<div><label for="name">Name:</label></div>
<input type="text" id="name" placeholder="Enter your name here...">
<small class="errorname" style="color:red;"></small>
<small class="validname" style="color: green;" ></small>
</div>
<div>
<div><label for="email">email:</label></div>
<input type="text" id="email" placeholder="Enter your email here..." >
<small class="erroremail" style="color:red;"></small>
<small class="validemail" style="color: green;" ></small>
</div>
<div>
<div><label for="password">password:</label></div>
<input type="text" id="password" placeholder="Enter your password here..." >
<small class="errorpass" style="color:red;" ></small>
<small class="validpass" style="color: green;" ></small>
</div>
<div>
<div><label for="phone">Phone number:</label></div>
<input type="text" id="phone" placeholder="Enter your phone number here..." >
<small class="errorphone" style="color:red;" ></small>
<small class="validphone" style="color: green;"></small>
</div>
<div>
<input type="submit" value="submit" >
</div>
</form>
<script src="./main.js" ></script>
</body>
</html>
getElementsByClassName has no definition for innerHTML because getElementsByClassName returns a NodeList object not an element. A NodeList is essentially a collection of elements.
Try it with getElementById as it works perfectly with your code. Also don't forget to set id for small tags.
Example would be :
if (resultemail == false || resultemail == "") {
document.getElementById("erroremail").innerHTML = "test email";
return false;
}
Or if you need to set it under class , You can set it by using the following code.
if (resultemail == false || resultemail == "") {
document.getElementsByClassName("erroremail")[0].innerHTML =
"لطفا ایمیل را با فرمت صحیح وارد کنید";
return false;
}
I am trying to submit a form in HTML after loading the page. It works when the form is refreshed. Otherwise, the form can't submit. My HTML page, complaint.html is below:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,700">
<link rel="stylesheet" href="jquery.mobile-1.4.5/demos/css/themes/default/jquery.mobile-1.4.5.min.css">
<link rel="stylesheet" href="jquery.mobile-1.4.5/demos/_assets/css/jqm-demos.css">
<script src="jquery.mobile-1.4.5/demos/js/jquery.js"></script>
<script src="jquery.mobile-1.4.5/demos/_assets/js/index.js"></script>
<script src="jquery.mobile-1.4.5/demos/js/jquery.mobile-1.4.5.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<script>
$(document).ready(function() {
$('#submt4').removeClass('ui-btn');
});
</script>
</head>
<body>
<div class="center container-fluid">
<div class="row">
<div class="col-xs-12">
<h2 align="center">COMPLAINTS</h2>
</div>
</div>
<div class="row">
<div class="col-xs-12"><input type="text" placeholder="Name" name="name" id="name">
</div>
</div>
<div class="row">
<div class="col-xs-12"><input type="text" placeholder="Mobile" name="mobile" id="mobile"></div>
</div>
<div class="row">
<div class="col-xs-12"><input type="text" placeholder="Vehicle No" name="vehicleno" id="vehicleno"></div>
</div>
<div class="row">
<div class="col-xs-12"><textarea rows="4" cols="50" name="complaint" id="complaint">Enter your complaint here...</textarea></div>
</div>
<div class="row">
<div class="col-xs-12" align="center">
<button class="btn btn-primary btn-lg " type="button" id="submt4" onClick="funComplaint();">SUBMIT</button></div>
</div>
</div>
</div>
<script type="text/javascript">
function funComplaint() {
var name = document.getElementById("name").value;
var mobile = document.getElementById("mobile").value;
var vehno = document.getElementById("vehicleno").value;
var complaint = document.getElementById("complaint").value;
var letters = /^[A-Za-z, ]+$/;
var numbers = /^[0-9]+$/;
var alphanum = /^[0-9a-zA-Z]+$/;
if (name == "" || mobile == "" || vehno == "" || complaint == "") {
alert("Please fill all fields........");
return false;
}
if (name.match(letters)) {} else {
alert("Name must have alphabet characters only");
document.getElementById('name').focus();
return false;
}
if (mobile.match(numbers)) {} else {
alert("Mobile number must have numeric characters only");
document.getElementById('mobile').focus();
return false;
}
if (mobile.length == 0 || mobile.length > 12 || mobile.length < 10) {
alert("Mobile number should not be empty / length be between 10 to 12");
document.getElementById('mobile').focus();
return false;
}
if (vehno.match(alphanum)) {} else {
alert("Vehicle number must have alphanumeric characters only");
document.getElementById('vehicleno').focus();
return false;
}
var x = new XMLHttpRequest();
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) {
var msg = x.responseText.trim();
if (msg == "Complaint Received") window.location = "home.html";
} else {
alert(msg);
}
}
}
x.open("GET", "http://localhost:8087/CarRental/com/selcar/getComplaint.jsp?name=" + name + "&mobile=" + mobile + "&vehno=" + vehno + "&complaint=" + complaint, true);
x.send();
}
</script>
</body>
</html>
After x.onreadystatechange definition you have one too many }.
Just remove one } before x.open(....
So the title pretty much says it all. The function validateForm is the one im having trouble with. Im trying to check to see if a field has not been entered then post a message (span tag) already there, yet i hide it using css. So i want that span tag that is hidden to show if one of the input fields have not been touched. I have functions to do the first name, last nam, email and phone number. I was also going to validate the check boxs and text areas in the validateform function as well. As this is a rather large website, some code will not be shown. But if you can spot the error i would greatly appreciate it.
<!DOCTYPE html>
<html lang="en">
<head>
<title>NONEYA</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--[if lt EI 9]>
<script src= "http://html5shim.googlecode.com/svn/trunk/html5.js">
</script>
<![endif]-->
<link rel="icon" href="images/hammerFavicon.ico" type="image/gif">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href = "css/custom/siteStyle.css">
<script src="js/main.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" ></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" "></script>
</head>
<body>
<!-- Header include -------------------------------------------------------------------------------------- -->
<?php include("includes/header.php"); ?>
<!-- Navigation include ---------------------------------------------------------------------------------- -->
<?php include("includes/navigation.php"); ?>
<!-- Main Content section -------------------------------------------------------------------------------- -->
<main role="main" class="container">
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Is this information correct?</p>
<div class="myButton">
<input type="submit" value="Yes" class="btnSize"/>
<input type="button" value="No" class="btnSize"/>
</div>
</div>
</div>
<div class="jumbotron">
<!-- Paragraph for text if needed ---------------------------------------------------------------- -->
<p class="lead">
<h2>Ask Us A Question</h2>
<br />
<!-- Question submission form ---------------------------------------------------------------- -->
<form action="" onsubmit="return validateForm()">
<div class = "fiftypercentofwidth">
<!--- First Name ------------->
<div class="form-group">
<div class="col">
<label for="fN">First Name</label>
<input type="text" onblur="validateFName(fN)" class="form-control" placeholder="First Name" id="fN">
</div>
</div>
<!--Last Name -------------->
<div class="form-group">
<div class="col">
<label for="lN">Last Name</label>
<input type="text" onblur="validateLName(lN)" class="form-control" placeholder="Last Name" id="lN">
</div>
</div>
<!-- Email -->
<div class="form-group">
<div class="col">
<label for="eMail">Email</label>
<input type="text" onblur="validateEmail(eMail)" class="form-control" placeholder="Email" id="eMail">
</div>
</div>
<br>
<!-- Phone Number -->
<div class="form-group">
<div class="col">
<label for="phoneNumber">Phone number</label>
<input type="text" onblur="validatePhoneNum(phoneNumber)" class="form-control" placeholder="Phone number" id="phoneNumber">
</div>
</div>
<br>
<!--Client Question Topic----------------------------------------------------------------------->
<h5>Select Question Category</h5>
<div class="form-group form-control">
<select id="qCategory">
<option disabled selected value>select an option</option>
<option value="Family Law">Family Law</option>
<option value="Housing Issues">Housing Issues</option>
<option value="Landlord/Tennant">Landlord/Tennant</option>
<option value="Social Security & Other Benefits">Social Security & Other Benefits</option>
<option value="Consumer Law">Cosnumer Law</option>
<option value="Education Law">Education Law</option>
<option value="Elder Law">Elder Law</option>
<option value="Immigration">Immigration</option>
<option value="Veterans">Veterans</option>
<option value="Post-conviction Issues">Post-Conviction Issues</option>
<option value="Driver's License/Id Issues">Driver's License/ ID Issues</option>
<option value="Criminal Law">Criminal Law</option>
<option value="Probate Matters">Probate Matters</option>
<option value="Estate Planning">Estate Planning</option>
<option value="Small Business Development">Small Business Development</option>
</select>
<br><br>
<!-- Client Question Details text field ------------------------------------------------------ -->
<h5>Enter your question:</h5>
<div class="form-group">
<textarea class="form-control" rows = "6" cols = "65"></textarea>
</div>
<br>
</div>
<br>
<div>
<span id="formError">Please Fill in Entire Form</span>
<button onclick="validateForm()" class="button button-block" id="cTModal">Create Ticket</button>
</div>
</div>
</form>
</p>
</div>
</main>
<!-- Footer include ---------------------------------------------------------------------------------------->
<?php include("includes/footer.php"); ?>
<!--Popup validation----------------------------------------------------------------------------------------
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("cTModal");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
---------------------------------------------------------------------------------------------------------->
</body>
</html>
**BEGINNING OF MY JAVASCRIPT CODE**
//Checks if user has pressed update without entering fields
function validateForm(){
if($('fN').innerHTML == ''){
$('formError').style.display = 'block';
return false;
} else if ($('lN').innerHTML == ''){
$('formError').style.display = 'block';
return false;
} else if ($('eMail').innerHTML == ''){
$('formError').style.display = 'block';
return false;
} else {
$("formError").hide();
return true;
}
}
function validateFName(x){
var re = /[a-zA-Z]$/;
if (x.value == ""){
x.style.background = '#e35152';
x.style.color = 'white';
x.value = "Please Fill in First Name";
return false;
} else {
if (!re.test(x.value)){
x.style.background = '#e35152';
x.style.color = 'white';
x.value = "Please Use Only Letters";
return false;
} else {
x.style.background = 'white';
x.style.color = 'black';
return true;
}
}
}
function validateLName(x){
var re = /[a-zA-Z]$/;
if (x.value == ""){
x.style.background = '#e35152';
x.style.color = 'white';
x.value = "Please Fill in Last Name";
return false;
} else {
if (!re.test(x.value)){
x.style.background = '#e35152';
x.style.color = 'white';
x.value = "Please Use Only Letters";
return false;
} else {
x.style.background = 'white';
x.style.color = 'black';
return true;
}
}
}
function validateEmail(x){
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (x.value == ""){
x.style.background = '#e35152';
x.style.color = 'white';
x.value = "Please Fill in Email";
return false;
} else {
if (!re.test(x.value)){
x.style.background = '#e35152';
x.style.color = 'white';
x.value = "You must enter a valid Email";
return false;
} else {
x.style.background = 'white';
x.style.color = 'black';
return true;
}
}
}
function validatePhoneNum(x) {
var re = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(x.value == "") {
x.style.background = '#e35152';
x.style.color = 'white';
x.value = "Please enter phone number xxx-xxx-xxxx";
return false;
} else {
if (!re.test(x.value)){
x.style.background = '#e35152';
x.style.color = 'white';
x.value = "Please enter phone number xxx-xxx-xxxx";
return false;
} else {
x.style.background = 'white';
x.style.color = 'black';
return true;
}
}
}
Use .value (not .innerHTML) to get the value of an input element. Also, to select by ID, you need to include '#' before the string. (Also, it's better to prefer strict equality over loose equality)
You can also clean up the code some by following DRY. Example:
function validateForm() {
const inputIDs = ['fN', 'lN', 'eMail'];
const formError = document.querySelector('#formError');
if (inputIDs.some(inputID => document.getElementById(inputID).value.length === 0)) {
formError.style.display = 'block';
return false;
} else {
formError.style.display = 'none';
return true;
}
}
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.
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.