I want to show the validation messages below the text fields that require it as well as the example that is in the image that I found
Example
I have the following text fields on my form, with their respective validation done in Javascript
//Function to validate ticket form
function validate_form() {
valid = true;
if (document.ticketForm.matricula.value == "") {
alert("Verify the data again, enter the license plate");
valid = false;
}
if (document.ticketForm.nombre.value == "") {
alert("Verify the data again, enter the name of the applicant");
valid = false;
}
return valid;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<form name="ticketForm" method="post" onchange="validate_form();">
<div id="informacionTicket" class="user">
<div class="card shadow mb-4">
<div class="card-body">
<div class="mb-4">
<div class="form-group">
<label for="ticketIdAppliInput">License:</label>
<input maxlength="9" required id="ticketIdAppliInput" type="text" name="matricula" onkeypress="if (isNaN(String.fromCharCode(event.keyCode))) return false;" class="form-control form-control-user" />
</div>
<div class="form-group">
<label for="ticketNameAppliInput">Full name:</label>
<input maxlength="100" id="ticketNameAppliInput" type="text" name="nombre" class="form-control form-control-user" />
</div>
<div class="form-group">
<label for="ticketEmailAppliInput">Email:</label>
<input maxlength="100" id="ticketEmailAppliInput" type="email" name="email" class="form-control form-control-user" />
</div>
</div>
</div>
</div>
</div>
<button type="button" id="submit" class="btn btn-primary btn-user btn-block">Send</button>
</form>
What I don't want is to be shown those annoying alert at the top of the form
I want the message to be displayed as in the example image
UPDATE:
Try this possible solution but when entering a value the message is no longer deleted
UPDATE:
I tried the possible solution of #JarlikStepsto but it still doesn't work properly
function validate(field) {
const validateables = document.getElementsByClassName('validateable');
const input = field;
if (!input.value == "") {
input.classList.add('invalid');
} else {
input.classList.remove('invalid');
}
if (!input.value == "") {
input.classList.add('invalid');
} else {
input.classList.remove('invalid');
}
}
input {
display: block;
}
.validation-message {
display: none;
}
input.validateable.invalid + .validation-message {
display: block;
color: red;
}
<div class="form-group">
<label class="required-field" name="matricula" for="ticketIdAppliInput">Matrícula:</label>
<input onchange="validate(this)" maxlength="9" required="required" id="ticketIdAppliInput" type="text" name="matricula" onkeypress="if (isNaN(String.fromCharCode(event.keyCode))) return false;" class="form-control form-control-user validateable"/>
<div class="validation-message">
Verifique la información nuevamente, ingrese la matricula</div>
</div>
<div class="form-group">
<label class="required-field" name="nombre" for="ticketNameAppliInput">Nombre completo:</label>
<input onchange="validate(this)" maxlength="100" id="ticketNameAppliInput" type="text" name="nombre" class="form-control form-control-user validateable" />
<div class="validation-message">
Verifique la información nuevamente, ingrese el nombre
</div>
</div>
UPDATE 2:
I will explain it better, I have two fields that matter to me that are compulsory "Matricula" and "Nombre Completo", when I am filling out the third field I do not get the validation message, this is the code I have, will I be doing something wrong?
function validate(field) {
const input = field;
if (!input.value || input.value.length === 0) {
input.classList.add('invalid');
} else {
input.classList.remove('invalid');
}
}
input {
display: block;
}
.validation-message {
display: none;
}
input.validateable.invalid + .validation-message {
display: block;
color: red;
}
<div class="form-group">
<label class="required-field" name="matricula" for="ticketIdAppliInput">Matrícula:</label>
<input onchange="validate(this)" maxlength="9" id="ticketIdAppliInput" type="text" name="matricula" onkeypress="if (isNaN(String.fromCharCode(event.keyCode))) return false;" class="form-control form-control-user validateable"/>
<div class="validation-message">
Verifique la información nuevamente, ingrese la matricula</div>
</div>
<div class="form-group">
<label class="required-field" name="nombre" for="ticketNameAppliInput">Nombre completo:</label>
<input onchange="validate(this)" maxlength="100" id="ticketNameAppliInput" type="text" name="nombre" class="form-control form-control-user validateable" />
<div class="validation-message">
Verifique la información nuevamente, ingrese el nombre
</div>
</div>
<div class="form-group">
<label class="required-field" name="email" for="ticketEmailAppliInput">Email:</label>
<input onchange="validate(this)" maxlength="100" id="ticketEmailAppliInput" type="email" name="email" class="form-control form-control-user validateable" />
<div class="validation-message">
Verifique la información nuevamente, ingrese el correo electronico
</div>
</div>
To show a validation message under the field you need a element to display it.
It could be any div, span or whatever you want.
In my example i will use a span to demonstrate how it works:
<input onchange="validate();" type="text" class="validateable" validation-pattern="[0-9]*" />
<div class="validation-message">Only numbers are allowed in this field!</div>
now in the js code we just have to validate for the pattern and set a input to invalid if it does not match the pattern:
function validate(){
const validateables = document.getElementsByClassName('validateable');
Array.prototype.forEach.call(validateables, input => {
const pattern = input.getAttribute('validation-pattern');
if(!input.value.match('^' + pattern + '$')){
input.classList.add('invalid');
} else {
input.classList.remove('invalid');
}
});
}
and the css to display validation text only if invalid:
.validation-message {
display: none;
}
input.validateable.invalid + .validation-message{
display: block;
color: red;
}
What this code does:
The JS function looks for every input with the class "validateable" and iterates over them. Each element should have an attribute with an validation pattern validation-pattern="[0-9]*" Now the function checks, if the value of the input matches the pattern and add a class invalid to the input or removes it.
In the css i defined an invisible div validation-message but if the element bevor this div is an validateable input field, that is invalid, the div will be displayed and you can see the validation message.
Working fidle:
https://jsfiddle.net/h687eomf/
UPDATE:
in your case, you just want to validate the field, that you are changing, have a look at my changed example fidle:
https://jsfiddle.net/h687eomf/2/
UPDATE 2:
A try to fix your snippet, assuming that a field is valid when its value is not empty and invalid if the value is empty:
function validate(field) {
const input = field;
if (!input.value || input.value.length === 0) {
input.classList.add('invalid');
} else {
input.classList.remove('invalid');
}
}
input {
display: block;
}
.validation-message {
display: none;
}
input.validateable.invalid + .validation-message {
display: block;
color: red;
}
<div class="form-group">
<label class="required-field" name="matricula" for="ticketIdAppliInput">Matrícula:</label>
<input onchange="validate(this)" maxlength="9" required="required" id="ticketIdAppliInput" type="text" name="matricula" onkeypress="if (isNaN(String.fromCharCode(event.keyCode))) return false;" class="form-control form-control-user validateable"/>
<div class="validation-message">
Verifique la información nuevamente, ingrese la matricula</div>
</div>
<div class="form-group">
<label class="required-field" name="nombre" for="ticketNameAppliInput">Nombre completo:</label>
<input onchange="validate(this)" maxlength="100" id="ticketNameAppliInput" type="text" name="nombre" class="form-control form-control-user validateable" />
<div class="validation-message">
Verifique la información nuevamente, ingrese el nombre
</div>
</div>
Related
If I enter the exact number of 300000, the form is submitted. Any other value below or above 300000 causes the error message to display. The error message should only display when the value is less than 300000. What's the error in my code?
document.addEventListener("DOMContentLoaded", function() {
document.querySelector('#sbutton').addEventListener('click', function(event) {
event.preventDefault();
let inputV = document.querySelector('#budget').value.trim();
let budgetRegex = /^3[0-9]{5,}/;
const errorMessage = document.querySelector('#errormsg');
let form = document.querySelector("form");
if (inputV == "" || !budgetRegex.test(inputV)) {
errorMessage.innerHTML = "Value should be at least 300,000.";
errorMessage.style.display = 'block';
} else {
errorMessage.innerHTML = "";
errorMessage.style.display = 'none';
form.submit();
}
});
});
<form action="https://dragonmm.xyz" method="post">
<div class="contact-box">
<div class="left1"></div>
<div class="right1">
<h2>Start</h2>
<label for="name"></label>
<input id="name" type="text" class="field" placeholder="Name" required>
<label for="email"></label>
<input id="email" type="text" class="field" placeholder="Email" required>
<label for="phone"></label>
<input id="phone" type="text" class="field" placeholder="Phone" required>
<label for="budget"></label>
<input id="budget" type="text" name="budget" class="field budgetInput" placeholder="Budget" required>
<div id="errormsg"></div>
</div>
</div>
<button type="submit" value="Send" class="btn1" id="sbutton">Send</button>
</form>
Use a numeric input field (type="number"). Use the min attribute of the field to limit the input (although a user can still input her own text). Next, convert values to Number, so you can do calculations.
Here's a minimal example, using event delegation.
Finally: you should always check values server side too.
document.addEventListener(`input`, handle);
function handle(evt) {
if (evt.target.id === "budget") {
if (+evt.target.value < +evt.target.min) {
// ^convert to Number
return document.querySelector(`#budgetError`)
.classList.remove(`hidden`);
}
return document.querySelector(`#budgetError`)
.classList.add(`hidden`);
}
}
#budgetError {
color: red;
}
.hidden {
display: none;
}
<input id="budget" type="number" min="300000"> budget
<div id="budgetError" class="hidden">
Not enough! We need at least 300,000</div>
can anyone help me to add this icon <i class="fas fa-check-circle"></i> if the background color changes to green using the following code:
document.querySelectorAll('input').forEach((inp) => {
inp.addEventListener('focusout', () => {
let value = inp.value.split(' ').join('')
if (value == '') {
inp.style.backgroundColor = "red";
} else {
inp.style.backgroundColor = "green";
let icon = document.createElement('i')
icon.classList.add('fas', 'fa-check-circle')
inp.appendChild(icon)
}
})
})
HTML Code
<section class="control-group">
<label class="control-label" for="company">Company</label>
<div class="controls">
<input
autofocus=""
class="input-xlarge"
id="company"
name="company"
placeholder="Company name"
type="text"
value=""
/>
</div>
</section>
<section class="control-group">
<label class="control-label" for="fname">Name</label>
<div class="controls two-col">
<input
class="input-medium"
id="fname"
name="fname"
placeholder="First name"
type="text"
value=""
/>
</div>
the excepted result is that the icon should be nest to every text field that has been filled.
You are trying tp append a child to an input. An input does not have children. You need to add it after the input. Also with your code, it would add a bunch of elements every time it loses focus.
document.querySelectorAll('input').forEach((inp) => {
let icon = document.createElement('i')
icon.classList.add('fas', 'fa-check-circle', 'hidden')
inp.after(icon);
inp.addEventListener('focusout', () => {
let value = inp.value.split(' ').join('')
if (value == '') {
inp.style.backgroundColor = "red";
icon.classList.add('hidden');
} else {
icon.style.display = 'inilne-block';
inp.style.backgroundColor = "green";
icon.classList.remove('hidden');
}
})
})
input {
padding-right: 20px;
}
input + i {
position: absolute;
margin-left: -20px;
}
i.hidden {
display: none;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
<input type="text"><input type="text"><input type="text">
You cannot add children to an input element. However, you can add the icon next to the input by means of insertAdjacentHTML().
document.querySelectorAll('input').forEach((inp) => {
inp.addEventListener('focusout', () => {
let value = inp.value.split(' ').join('')
if (value == '') {
inp.style.backgroundColor = "red";
} else {
inp.style.backgroundColor = "green";
inp.insertAdjacentHTML('afterend', '<i class="fas fa-check-circle">Your icon here</i>');
}
})
})
<input type="text">
If you want the icon "inside" the input, then you need to use CSS to set it as a background image, which is not related to "adding a HTML element using JavaScript".
I would suggest that rather than adding new elements in response to user input, you build all the elements into your html, and then hide/show/style them appropriately with a css class or two:
document.querySelectorAll('input').forEach((inp) => {
inp.addEventListener('focusout', () => {
const parent = inp.parentNode;
let value = inp.value.split(' ').join('');
if (value == '') {
parent.classList.remove("valid");
parent.classList.add("invalid");
} else {
parent.classList.remove("invalid");
parent.classList.add("valid");
}
});
});
.controls i {
display: none;
}
.controls.valid input {
background-color: green;
}
.controls.valid i {
display: inline;
}
.controls.invalid input {
background-color: red;
}
<section class="control-group">
<label class="control-label" for="company">Company</label>
<div class="controls">
<input
autofocus=""
class="input-xlarge"
id="company"
name="company"
placeholder="Company name"
type="text"
value=""
/>
<i class="fas fa-check-circle">test</i>
</div>
</section>
<section class="control-group">
<label class="control-label" for="fname">Name</label>
<div class="controls two-col">
<input
class="input-medium"
id="fname"
name="fname"
placeholder="First name"
type="text"
value=""
/>
<i class="fas fa-check-circle">test</i>
</div>
</section>
elem = document.createElement("<div id='myID'> my Text </div>");
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 have a form with 3 inputs: 2 text inputs for a Username and E-mail and a third password input for, you guessed it, a password.
I'm validating these input fields in JQuery and when an input is either empty or doesn't match it's format, it adds a class to the input with a red border. The code goes as follows:
if ($("input#username").val().length < 6) {
$("input#username").addClass('input-error');
next_step = false;
} else if (!isEmail($("#email").val())) {
$("#email").addClass('input-error');
next_step = false;
} else if (!isPassword($("#pwd").val())) {
$("#pwd").addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
next_step = true;
}
It works perfectly with both Username and E-mail fields, and it also works if the Password field is empty, but even though it validates perfectly, the addClass() doesn't work if the Password doesn't meet it's requirements (At least one Uppercase letter and one number).
This is what the browser console shows:
As you can see, it kind of adds the class, but then not really.
What is happening? If you need the HTML code and/or the CSS code, tell me!
Thanks for your attention!
EDIT
Here is the HTML and CSS as requested:
<fieldset>
<div class="form-bottom">
<img src="img/gbsnlogo.svg" alt="GBSN Research" name="GBSN Research" width="50%" class="signupLogo" />
<br>
<br>
<br>
<div class="form-group">
<label for="username"><h1>USERNAME:</h1></label>
<input type="text" class="form-control" id="username" placeholder="Enter username..." name="username">
</div>
<div class="form-group">
<label for="email"><h1>E-MAIL:</h1></label>
<input type="text" class="form-control" id="email" placeholder="Enter e-mail..." name="email">
</div>
<div class="form-group">
<label for="pwd"><h1>PASSWORD:</h1></label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password..." name="pwd">
</div>
<div class="text-center">
<button type="button" class="btn-next btn-nav"><h1>NEXT</h1></button>
</div>
</div>
</fieldset>
and the CSS:
.form-control {
height: 40px;
border: 2px solid black;
border-radius: 0;
font-size: 14px;
}
.form-control:focus {
border: 2px solid black;
box-shadow: 0;
}
.input-error {
border-color: #FF2859;
}
This is working for me.
Please comment what is still not working if you have this kind of setup?
function isEmail(email) { // dummy example
return email.indexOf("#")>1;
}
function isPassword(passwd) { // dummy example
return passwd.indexOf("x")>=0; // must contain x
}
$(function() {
$(".btn-next").on("click", function() {
$(".form-group input").removeClass('input-error');
var next_step = true,
user = $("#username").val(),
email = $("#email").val(),
pwd=$("#pwd").val();
if (user.length < 6) {
$("#username").addClass('input-error');
next_step = false;
} else if (!isEmail(email)) {
$("#email").addClass('input-error');
next_step = false;
} else if (!isPassword(pwd)) {
$("#pwd").addClass('input-error');
next_step = false;
}
console.log(next_step);
});
});
.form-control {
height: 40px;
border: 2px solid black;
border-radius: 0;
font-size: 14px;
}
.form-control:focus {
border: 2px solid black;
box-shadow: 0;
}
.input-error {
border-color: #FF2859;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<fieldset>
<div class="form-bottom">
<img src="img/gbsnlogo.svg" alt="GBSN Research" name="GBSN Research" width="50%" class="signupLogo" />
<br>
<br>
<br>
<div class="form-group">
<label for="username"><h1>USERNAME:</h1></label>
<input type="text" class="form-control" id="username" placeholder="Enter username..." name="username">
</div>
<div class="form-group">
<label for="email"><h1>E-MAIL:</h1></label>
<input type="text" class="form-control" id="email" placeholder="Enter e-mail..." name="email">
</div>
<div class="form-group">
<label for="pwd"><h1>PASSWORD:</h1></label>
<input type="text" class="form-control" id="pwd" placeholder="Enter password..." name="pwd">
</div>
<div class="text-center">
<button type="button" class="btn-next btn-nav"><h1>NEXT</h1></button>
</div>
</div>
</fieldset>
From what I see from the image you posted
I can only speculate this is what happened.
The line [input#pwd.form-control.input-error] was evaluated immediately when it got printed to the console. So that mean at that time, the dom does have the class input error in it. However, when you expand it, the dom got re-evaluated again. And at that time, the dom's class input-error got removed, so you don't see it anymore. I was able to prove this by running $('#pwd').addClass('input-error') and $('#pwd').removeClass('input-error') in that order, image below
Based on that, I suspect you have another logic in the code that remove the class shortly after you have added the class to the dom, highly possibly $(this).removeClass('input-error');.
So I have a form and a script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" id="contact">
<label for="prenom">Prénom</label>
<input type="text" id="prenom" name="prenom" placeholder="Votre prénom.." class="champ">
<label for="nom">Nom</label>
<input type="text" id="nom" name="nom" placeholder="Votre nom.." class="champ"><br/>
<label for="email">Email</label>
<input type="text" id="email" name="email" placeholder="Votre nom.." class="champ"><br/>
<label for="country">Pays</label>
<select name="country" id="country" class="champ">
<option value="france">France</option>
<option value="Canada">Canada</option>
<option value="Suisse">Suisse</option>
<option value="Belgique">Belgique</option>
</select><br/>
<label for="sujet">Sujet : </label>
<textarea class="champ" name="sujet" id="sujet" placeholder="Exprimez-vous.." style="height:200px; width=600px;"></textarea ><br/>
<input type="submit" value="Envoyer" class="champ" id="envoi">
</form>
<div id="errorMessage"></div>
<script type="text/javascript">
var errorMessage="";
$("#envoi").click(function () {
if($("#prenom").val()==""){
errorMessage+="<p>Remplissez votre prénom!</p>";
}
if($("#nom").val()==""){
errorMessage+="<p>Remplissez votre nom!</p>";
}
if($("#email").val()==""){
errorMessage+="<p>Remplissez votre email!</p>";
}
if($("#pays").val()==""){
errorMessage+="<p>Sélectionnez votre pays!</p>";
}
if($("#sujet").val()==""){
errorMessage+="<p>Remplissez votre message!</p>";
}
if(errorMessage!=""){
alert("hey");
$("#errorMessage").html(errorMessage);
}
});
</script>
I have a problem with this :
if(errorMessage!=""){
alert("hey");
$("#errorMessage").html(errorMessage);
}
I wish it would display the error message in
right before the script. The program does get into the if condition, because the alert appears. However, it does not display the error.
What am I doing wrong please?
Thanks,
It's due to your page is being reloaded after being submitted.
If you want to display an error (validation) you should return false.
if(errorMessage!=""){
alert("hey");
$("#errorMessage").html(errorMessage);
return false;
}
simply just add the following in your code to Acheive your goal
e.preventDefault();
Here is the working jsfiddle:https://jsfiddle.net/1b5pcqpL/
The button trigger you are using is of type=submit which is causing your form to submit.
Instead try using type=button and submit the form after jquery validation.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" id="contact">
<label for="prenom">Prénom</label>
<input type="text" id="prenom" name="prenom" placeholder="Votre prénom.." class="champ">
<label for="nom">Nom</label>
<input type="text" id="nom" name="nom" placeholder="Votre nom.." class="champ"><br/>
<label for="email">Email</label>
<input type="text" id="email" name="email" placeholder="Votre nom.." class="champ"><br/>
<label for="country">Pays</label>
<select name="country" id="country" class="champ">
<option value="france">France</option>
<option value="Canada">Canada</option>
<option value="Suisse">Suisse</option>
<option value="Belgique">Belgique</option>
</select><br/>
<label for="sujet">Sujet : </label>
<textarea class="champ" name="sujet" id="sujet" placeholder="Exprimez-vous.." style="height:200px; width=600px;"></textarea ><br/>
<input type="button" value="Envoyer" class="champ" id="envoi">
</form>
<div id="errorMessage"></div>
<script type="text/javascript">
$("#envoi").click(function () {
var errorMessage="";
if($("#prenom").val()==""){
errorMessage+="<p>Remplissez votre prénom!</p>";
}
if($("#nom").val()==""){
errorMessage+="<p>Remplissez votre nom!</p>";
}
if($("#email").val()==""){
errorMessage+="<p>Remplissez votre email!</p>";
}
if($("#pays").val()==""){
errorMessage+="<p>Sélectionnez votre pays!</p>";
}
if($("#sujet").val()==""){
errorMessage+="<p>Remplissez votre message!</p>";
}
if(errorMessage!=""){
alert("hey");
$("#errorMessage").html(errorMessage);
}
else{
$("#contact").submit();
}
});
</script>
The message is appended to the DOM, what happens is that the form get submitted and that causing the page to reload (happens so fast you can't notice it). You'll have to prevent the default behavior of the event (which is submitting the form right after the alert and the message is appended to the DOM)!
Note: Change your click event to the submit event to prevent the user from submitting via enter key as well.
<script type="text/javascript">
$("#contact").submit(function (event) { // listen to the submit event on the form #contact itself (event is needed so we can prevent its default behavior)
var errorMessage = ""; // this should be here
// ...
if(errorMessage != ""){
alert("hey");
$("#errorMessage").html(errorMessage);
event.preventDefault(); // stop the submit (we encountered an error so mission abort :D)
}
});
</script>
<head>
<title>jQuery</title>
<script type="text/javascript" src="jquery.min.js"></script>
<style type="text/css">
body {
font-family: helvetica, sans-serif;
font-size:130%;
}
input {
padding: 5px 5px 12px 5px;
font-size: 25px;
border-radius: 5px;
border: 1px solid grey;
width:320px;
}
label {
position: relative;
top:12px;
width:200px;
float: left;
}
#wrapper {
width: 550px;
margin: 0 auto;
}
.form-element {
margin-bottom: 10px;
}
#submitButton {
width: 130px;
margin-left: 200px;
}
#errorMessage {
color: red;
font-size: 90% !important;
}
#successMessage {
color: green;
font-size: 90% !important;
display:none;
margin-bottom:20px;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="successMessage">You've done it! Congratulations.</div>
<div id="errorMessage"></div>
<div class="form-element">
<label for="email">Email</label>
<input type="text" name="email" id="email" placeholder = "eg. yourname#gmail.com">
</div>
<div class="form-element">
<label for="phone">Telephone</label>
<input type="text" name="phone" id="phone" placeholder = "eg. 0123456789">
</div>
<div class="form-element">
<label for="password">Password</label>
<input type="password" name="password" id="password">
</div>
<div class="form-element">
<label for="passwordConfirm">Confirm Password</label>
<input type="password" name="passwordConfirm" id="passwordConfirm">
</div>
<div class="form-element">
<input type="submit" id="submitButton" value="Sign Up"
</div>
</div>
<script type="text/javascript">
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$("#submitButton").click(function() {
var errorMessage = "";
var fieldsMissing = "";
if ($("#email").val() == "") {
fieldsMissing += "<br>Email";
}
if ($("#phone").val() == "") {
fieldsMissing += "<br>Telephone";
}
if ($("#password").val() == "") {
fieldsMissing += "<br>Password";
}
if ($("#passwordConfirm").val() == "") {
fieldsMissing += "<br>Confirm Password";
}
if (fieldsMissing != "") {
errorMessage += "<p>The following field(s) are missing:" + fieldsMissing;
}
if (isEmail($("#email").val()) == false) {
errorMessage += "<p>Your email address is not valid</p>";
}
if ($.isNumeric($("#phone").val()) == false) {
errorMessage += "<p>Your phone number is not numeric</p>"
}
if ($("#password").val() != $("#passwordConfirm").val()) {
errorMessage += "<p>Your passwords don't match</p>";
}
if (errorMessage != "") {
$("#errorMessage").html(errorMessage);
} else {
$("#successMessage").show();
$("#errorMessage").hide();
}
});
</script>
</body>
How come it works in this case?