So basically, I'm trying to do client side validation through JavaScript, but the code does not seem to be working. I am not getting any alert box. Below is HTML Form and JavaScript. I have skipped html and Body tags for obvious reasons. Can someone look over and see where am I making a mistake?
HTML form
<div class="container" >
<h1 style="text-align: center;">Online Vaccine Registration Form</h1>
<h1 style="text-align: center;">Developed by yourname</h1>
<form method="post" name="vacform" onsubmit=" return validateForm()">
<table>
<div class="row">
<div class="form-group col-md-6">
<label for="Name">Name : </label>
<input type="text" class="form-control" name="name" placeholder="Name">
</div>
<div class="form-group col-md-6">
<label for="CNIC" >CNIC : </label>
<input type="text" class="form-control" name="CNIC" placeholder="CNIC">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="Mob">Mobile : </label>
<input type="number" class="form-control" name="Mob" placeholder="Mobile">
</div>
<div class="form-group col-md-6">
<label for="Dob" >DoB : </label>
<input type="date" class="form-control" name="DoB">
</div>
</div>
<div class="form-group">
<label for="cen">Nearby centre</label>
<select class="form-control" id="sel1">
<option selected disabled>Select your Nearest Centre</option>
<option>Karachi West</option>
<option>Karachi East</option>
<option>Karachi North</option>
<option>Karachi Central</option>
<option>Malir</option>
</select>
</div>
</table>
<button type="button" class="btn btn-primary">Submit</button>
</form>
</div>
JavaScript
function validateForm()
{
var varname = document.vacform.name.value;
var varcnic = document.vacform.CNIC.value;
var varMob = document.vacform.Mob.value;
var varDoB = new Date(DoB);
var limitdate = new Date('2010-01-01');
var CNlength = 13;
var num = /^[0-9]+$/;
var str = /^[A-Za-z]+$/;
if(document.vacform.name.value!="")
{
if(document.vacform.CNIC.value!="")
{
if(document.vacform.Mob.value!="")
{
if(document.vacform.DoB.value!="")
{
if(varname.match(str))
{
if(varcnic.lenght == CNlength)
{
if(varcnic.match(num))
{
if(varDoB.getYear() < limitdate.getYear())
{
alert("All types of Validations have been done")
return true;
}
else
{
alert("Date should be less than 01-01-2010")
return false;
}
}
else
{
alert("CNIC field should have numbers only")
return false;
}
}
else
{
alert("CNIC lenght should be 13")
return false;
}
}
else
{
alert("Name can only contain letters")
return false;
}
}
else
{
alert("Date of Birth must be entered")
return false;
}
}
else
{
alert("Please Enter your mobile number")
return false;
}
}
else
{
alert("CNIC number Required")
return false;
}
}
else
{
alert("Name field can not be empty")
return false;
}
}
</script>
You call the function from the onsubmit event handler, however you never submit the form so it can't be triggered.
<button type="button" class="btn btn-primary">Submit</button>
This kind of button is for hooking JS into. It isn't a submit button.
Set type="submit" or remove the type attribute entirely (submit is the default).
Also address the errors in your HTML that a validator would highlight.
Related
i am trying to validate my html form using javascript. the validation works but it still submits.
ie. when clicking submit a text will appear saying "first name is required" but then still submits.
here is the javascript code:
function validateForm(form) {
formValid = true;
for(i = 0; i < form.length; i++) {
if(!requiredInput(form[i]))
formValid = false;
}
return formValid;
}
function requiredInput(element) {
if(!element.value.length) {
document.getElementById(element.id + 'Error').style.display = "inline-block";
return false;
} else {
document.getElementById(element.id + 'Error').style.display = "none";
return true;
}
return;
}
and here is the html code for the form:
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get" onsubmit="return validateForm(this);">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit" >
</div>
</form>
im not sure why it still submits.
EDIT: i need to debug this code and not change all of it
EDIT: i can not change the html code for this, i am to debug the javascript only
I think you need validate if its type submit :
function validateForm(form) {
formValid = true;
for(i = 0; i < form.length; i++) {
if(form[i].type != "submit"){
if(!requiredInput(form[i])){
formValid = false;
}
}
}
return formValid;
}
Your validation has the correct structure, however, if there is any JavaScript error, the "return false" will not cancel the form submission.
Go to your developer console and manually invoke the validateForm function. You can give the form an ID:
<form id="myform"...
Then, you can reference this in the console:
validateForm(document.getElementById('form'));
You will see a JavaScript error. Fix the error and your form will be intercepted.
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get"
onsubmit="return validateForm(event)">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit">
</div>
<script type="text/javascript">
function validateForm(e) {
form = e.target;
formValid = true;
for (i = 0; i < form.length; i++) {
if (!requiredInput(form[i]))
formValid = false;
}
return formValid;
}
function requiredInput(element) {
if (element.type == 'submit') {
return true;
}
if (element.value.length == 0) {
document.getElementById(element.id + 'Error').style.display = "inline-block";
return false;
} else {
document.getElementById(element.id + 'Error').style.display = "none";
return true;
}
}
this should work
Actually You can do it simple way, see below,
Modify your HTML
I remove onsubmit attribute and add form to ID
<form id="dsds" action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit" >
</div>
Remove your JS function and do like this,
$("#dsds").submit(function(e){
//call your functions here
return false; // return true if you want to submit the form
});
See the example,
JSFille
Use preventDefault() to disable the submit.
function validateForm(event, form) {
formValid = true;
for (i = 0; i < form.length; i++) {
if (!requiredInput(form[i])) {
formValid = false;
break;
}
}
if (!formValid) {
event.preventDefault();
}
return formValid;
}
And pass the event object in the onsubmit function like below.
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get" onsubmit="validateForm(event, this);">
function validateForm(form) {
formValid = true;
try {
for (i = 0; i < form.length; i++) {
if (!requiredInput(form[i]))
formValid = false;
}
} catch (error) {
console.error("validateForm=>", error)
}
return formValid;
}
function requiredInput(element) {
try {
const elementInputError = document.getElementById(element.id + 'Error');
if (!element.value.length) {
elementInputError && setDisplayError(elementInputError,"inline-block");
return false;
} else {
elementInputError && setDisplayError(elementInputError,"none");
return true;
}
} catch (error) {
console.error("requiredInput=>", error)
return false;
}
}
function setDisplayError(element,value) {
try {
element.style.display =value;
} catch (error) {
console.error("setDisplayError=>", error)
}
}
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get"
onsubmit="return validateForm(this);">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit">
</div>
</form>
The problem arose because it also validated the send button and because it did not have the termination of the failed id it could not find the item and an error occurred. Then when the error occurred it did not return anything the function and redirect you to the form action page.
I made a JQuery function to check for empty required fields inside a closed custom dropdown.
If a required field is empty inside one of the dropdown and if the dropdown is currently closed I want the dropdown to open and if there are no empty values in the required fields I want the dropdown to close.
The problem is that the required fields aren't accessible if the dropdowns are closed and I tried to fix that problem with this function.
For some reason, it only checks for these input fields if the form is submitted at least once and the required fields are opened at least once.
find(':input[required]') doesn't give any output if the dropdown isn't opened at least once, once u open and close the dropdown the function works.
This is the function:
function dropdown_required() {
var required = 0;
$('#visible_fields').find(':input[required]').each(function () {
if (!this.value) {
for (var i = 1; i < 15; i++) {
$('.form_' + i).find(':input[required]').each(function () {
$(this).prop('required', false);
});
}
required++;
}
});
if (required == 0) {
for (var i = 1; i < 15; i++) {
var empty = 0;
$('.form_' + i).find(':input[required]').each(function ()
{
if(!this.value) {
empty++;
}
});
if (empty !== 0) {
if ($(".arrow_" + i).hasClass("rotate_2")) {
$(".arrow_" + i).addClass("rotate_1").removeClass("rotate_2");
$(".form_" + i).fadeToggle();
}
} else if ($(".arrow_" + i).hasClass("rotate_1")) {
$(".arrow_" + i).addClass("rotate_2").removeClass("rotate_1");
$(".form_" + i).fadeToggle();
}
}
}
}
This is the html:
<form method="POST" autocomplete="off" enctype="multipart/form-data" target="_self"
action="/contacten/leveranciers/iframe{{ ($leverancier == null ? '' : '/' . $leverancier->cot_id) }}">
{{ csrf_field() }}
<div id="visible_fields">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="organisatie">Organisatie</label>
<input type="text" name="organisatie" id="organisatie" blocked=",;()/" hk="a"
value="{{ ($leverancier == null ? old('organisatie') : $leverancier->cot_organisatie) }}"
class="form-control inputblocked">
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="postcode">Postcode</label>
<input type="text" name="postcode" id="postcode" filter="a-zA-Z0-9" maxlength="6"
value="{{ ($leverancier == null ? old('postcode') : $leverancier->cot_postcode) }}"
class="form-control inputfilter filter_postcode">
</div>
</div>
</div>
//all visible input fields outside of the dropdowns
</div>
<label class="toggle_1">Controles<span class="arrow_1 glyphicon glyphicon-menu-left"
aria-hidden="true"></span></label>
<div class="form_1">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="bkr">BKR</label>
<select name="bkr" class="form-control" required>
<option selected hidden></option>
<option value="10">BKR toetsing open</option>
<option value="11">BKR toetsing accoord</option>
<option value="12">Vrijgesteld van BKR toetsing</option>
</select>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="bkr_bestand">BKR bestand</label>
<input type="file" name="bkr_bestand" id="bkr_bestand"
data-default-file=""
class="form-control dropify">
<input type="hidden" name="verwijder_foto" class="verwijder_foto" value="0">
</div>
</div>
</div>
</div>
<div class="form-group">
<input type="hidden" id="input_iframe" name="input_iframe" value="">
<button type="submit" onclick="dropdown_required()"
class="btn btn-primary">Toevoegen </button>
</div>
</form>
</div>
</body>
</html>
Your function checks if your arrow element has the class rotate_2. The code you pasted has neither rotate_1 or rotate_2 and no else block, so the toggle never executes.
Problem demonstration:
// This group has empty mandatory elements
var empty = 1;
$('#validate').click(function() {
if (empty !== 0) {
console.log("I have empty elements!");
// From your comments, this might be backwards
if ($(".arrow_1").hasClass("rotate_2")) {
console.log("I'm going to show them");
$(".arrow_1").addClass("rotate_1").removeClass("rotate_2");
$(".form_1").fadeToggle();
}
// This is missing in the code
else {
console.log("I wasn't invited to the party");
}
// -------
} else if ($(".arrow_1").hasClass("rotate_1")) {
console.log("I'm out, I don't have empty elements...");
$(".arrow_1").addClass("rotate_2").removeClass("rotate_1");
$(".form_1").fadeToggle();
}
});
$('#simulate').click(function() {
// Simulates manually opening and closing
// In short, add rotate_2 class as if it's been toggled
$('.arrow_1').addClass('rotate_2');
console.log("Toggled manually");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="toggle_1">Controles<span class="arrow_1 glyphicon glyphicon-menu-left"
aria-hidden="true"></span></label>
<div class="form_1">
<div>Some form elements</div>
</div>
<button id="validate">Validate</button>
<button id="simulate">Simulate</button>
This is my first real project which involves form validation. I am experiancing a problem which I can not find the solution to.
The objective is this, there is a continue button which will be activated once all the field inputs have been passed as valid. I am going about this by creating seperate variables, all initially set as false, devoted to checking each input field. When the user has entered correct validation data, the variable is set to true.
I then run an if statement to check if all the variables are set to true, and if so, I activate the continue button which, when clicked, slides the next part of the form into the page.
HTML:
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" id="submit" value="CONTINUE">
</div>
</div>
</div>
JAVASCRIPT / JQUERY:
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input",function(){
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility","visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)){
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility","visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility","hidden");
emailValidated = true;
}
})
//name validation check//
nameField.on("input",function(){
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility","visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility","hidden");
nameValidated = true;
}
})
//contact number validation check//
numberField.on("input",function(){
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility","visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility","hidden");
numberValidated = true;
}
})
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
})
at the moment, I am simply using the alert prompt to test if it is working, but it fails.
As mentioned, this is my first real form validation. Any other tips or advice would be greatly appreciated. Thanks for the help in advance.
There were a couple things that I found from copying pasting your snippets of code. 1 there was an ending "})" without a beginning $(document).ready(function(){ ". 2 none of your ".on" statements had an ending semi colon.
Here is my javascript with a small change
$(document).ready(function () {
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input", function () {
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)) {
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility", "hidden");
emailValidated = true;
enableContinue();
}
});
//name validation check//
nameField.on("input", function () {
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility", "visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility", "hidden");
nameValidated = true;
enableContinue();
}
});
//contact number validation check//
numberField.on("input", function () {
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility", "visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility", "hidden");
numberValidated = true;
enableContinue();
}
});
enableContinue = function () {
if (emailValidated && nameValidated && numberValidated) {
$('#submit').prop('disabled', false);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" class="btn btn-primary" id="submit" disabled="disabled" value="CONTINUE">
</div>
</div>
</div>
Your form CONTINUE button becomes enables once all fields have a value. Note: I did not try to improve your javascript any, just made it work.
Right now you synchronically check validation variables at script, so they are all false. You have to asynchronically check them after form submit. Just add event listener to form submit to check variables like this:
document.getElementById('#form').addEventListener('submit', function(){
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
});
Don't forget to set id to your form.
You may be able to save a lot of work if you leverage some of the built in HTML5 form validation. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
This simple example adds a new field every time you submit the form, as long as the existing fields are valid. You would need to test the state of the form to see if you should be adding another section or submitting.
$('form').on('submit', function() {
$(this).find('fieldset').append('<input type="text" required />');
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<input type="text" required />
</fieldset>
<input type="submit" id="submit" value="continue" />
</form>
After clicking submit the form is not producing errors next to the input fields ,it refreshes the page and clears all the fields.
HTML:
<form id="mc-form" method="POST">
<div class="form-group col-xs-12 ">
<label for="name" hidden>שם פרטי</label>
<input type="text" name="name" id="name" class="cv form-control" placeholder="שם פרטי" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="lastName" hidden>שם משפחה</label>
<input type="text" name="lastName" id="lastName" class="cv form-control" placeholder="שם משפחה" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="phone" hidden>טלפון</label>
<input type="text" name="phone" id="phone" class="cv form-control" placeholder="טלפון" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="email" hidden>דואר אלקטרוני</label>
<input type="email" name="email" id="email" class="cv form-control" placeholder="דואר אלקטרוני" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="subject" hidden>נושא</label>
<input type="text" name="subject" id="subject" class="cv form-control" placeholder="נושא" onkeyup='validateMessage()'>
</div>
<div class="form-group col-xs-12 ">
<label for="message" hidden>הודעה</label>
<textarea name="message" id="message" class="cv form-control message" placeholder="השאירו את הודעתכם פה" rows="4" cols="50" onkeyup='validateMessage()'></textarea>
</div>
<!-- <input type="submit" id="submit-button" class="btn btn-custom-outline " value="שלח" > -->
<button onclick='return validateForm()' class="btn btn-custom-outline " id="submit-button">שלח</button>
<span class='error-message' id='submit-error'></span>
<br>
<!-- <div class="success"><?= $success ?></div>-->
<!--<span class="error"></span> -->
</form>
My JavaScript:
function validateName() {
var name = document.getElementById('name').value;
if(name.length == 0) {
producePrompt('Name is required', 'name-error' , 'red')
return false;
}
if (!name.match( /^[a-zא-ת]+(\s[a-zא-ת]+)*$/i)) {
producePrompt('Letters only please.','name-error', 'red');
return false;
}
producePrompt('Valid', 'name-error', 'green');
return true;
}
function validatePhone() {
var phone = document.getElementById('phone').value;
if(phone.length == 0) {
producePrompt('Phone number is required.', 'phone-error', 'red');
return false;
}
if(!phone.match(/^[0-9]{10}$/)) {
producePrompt('Only digits, please.' ,'phone-error', 'red');
return false;
}
producePrompt('Valid', 'phone-error', 'green');
return true;
}
function validateEmail () {
var email = document.getElementById('email').value;
if(email.length == 0) {
producePrompt('Email Invalid','email-error', 'red');
return false;
}
if(!email.match(/^[A-Za-z\._\-[0-9]*[#][A-Za-z]*[\.][a-z]{2,4}$/)) {
producePrompt('Email Invalid', 'email-error', 'red');
return false;
}
producePrompt('Valid', 'email-error', 'green');
return true;
}
/*function validateMessage() {
var message = document.getElementById('contact-message').value;
var required = 30;
var left = required - message.length;
if (left > 0) {
producePrompt(left + ' more characters required','message-error','red');
return false;
}
producePrompt('Valid', 'message-error', 'green');
return true;
}*/
function validateForm() {
if (!validateName() || !validatePhone() || !validateEmail() ) {
jsShow('submit-error');
producePrompt('Please fix errors to submit.', 'submit-error', 'red');
setTimeout(function(){jsHide('submit-error');}, 2000);
return false;
}
else {
}
}
function jsShow(id) {
document.getElementById(id).style.display = 'block';
}
function jsHide(id) {
document.getElementById(id).style.display = 'none';
}
function producePrompt(message, promptLocation, color) {
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;
}
My scrips are in index.html , same page the form is, in the end :
<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.3/umd/popper.min.js" ></script>
<script src="js/bootstrap.min.js" ></script>
<!-- [ SLIDER SCRIPT ] -->
<script type="text/javascript" src="js/SmoothScroll.js"></script>
<script src="js/script.js" ></script>
<script src="js/validateform.js" ></script>
After clicking submit the form is not producing errors next to the input fields ,it refreshes the page and clears all the fields.
The issue that you are running into in calling
producePrompt('Email Invalid','email-error', 'red');
and any other where you are not passing name-error an error is occurring as there is no element with the id email-error they all have the same id. When the error is thrown the function returns undefined instead of false causing the form to be submitted.
When using Chrome dev tools you can go into settings and check preserve log this will allow you to see errors even after the page refreshes.
As to checking for all errors instead of just the first one...
the if (!validateName() || !validatePhone() || !validateEmail() ) {
or statements here mean the first one that false causes the rest to not be checked. Instead you could do something like the following
var vn = validateName();
var vp = validatePhone();
var ve = validateEmail();
if (!vn || !vp || !ve) {
I am trying to get a form with multiple fields validate when the submit button is pressed.
If a field is invalid then a message appears next to the field. I can get one of the invalid messages to appear but not all of them. The function I am using is below.
function checkForm() {
document.getElementById("test").onsubmit=function(){
var title = document.getElementById("titles");
if (title.selectedIndex == -1) {
return null;
}
var email = document.getElementById('email');
//Regular Expression for checking email
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
document.getElementById("errEmail").style.display="inline";
return false;
}
if(document.getElementById("fname").value==""){
document.getElementById("errfName").style.display="inline";
return false;
}
else {
return true;
}
if(document.getElementById("lname").value==""){
document.getElementById("errlName").style.display="inline";
return false;
}
else {
return true;
}
}
}
html below
<form name ="reg" id="test">
<fieldset id="controls">
<div>
<label for="title">Title: </label>
<select id="titles">
<option value="mr" selected="selected">Title</option>
<option value="mr">Mr.</option>
<option value="mrs">Mrs.</option>
<option value="ms">Ms.</option>
<option value="miss">Miss</option>
</select>
</div>
<div>
<label for="fname">First Name: </label>
<input id="fname" type="text"><span id="errfName" class="error">* Please Enter a First Name</span>
</div>
<div>
<label for="lname">Last Name: </label>
<input id="lname" type="text"><span id="errlName" class="error">* Please Enter a Last Name</span>
</div>
<div>
<label for="email">Email: </label>
<input id="email" type="text" size="40"><span id="errEmail" class="error">* Please enter a valid email</span>
</div>
<div>
<input type="submit" value="submit">
</div>
</fieldset>
</form>
</body>
</html>
try this:
function checkForm() {
var errors = [];
document.getElementById("test").onsubmit=function(){
var title = document.getElementById("titles");
if (title.selectedIndex == -1) {
return null;
}
var email = document.getElementById('email');
//Regular Expression for checking email
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
errors.push("errEmail");
}
if(document.getElementById("fname").value==""){
errors.push("errfName");
}
if(document.getElementById("lname").value==""){
errors.push("errlName");
}
if(errors.length > 0 ){
for(var i=0;i<errors.length;i++){
document.getElementById(errors[i]).style.display="inline";
}
return false;
}else{
return true
}
}
}