Validation in JavaScript - how to make the red border disappear? - javascript

At the moment, when a field is empty and not valid the field turns red and a describing text shows up. But how do I make the field and text disappear when the user fill in the field correctly?
code in HTML:
<label for="email"><b>Email</b></label>
<label id="lblemail" style="color: red; visibility: hidden; float: right;">Invalid email</label><br>
<input type="text" placeholder="Enter Email" name="email" id="email"><br>
code in JS:
var email = document.getElementById("email");
if (email.value.trim() == "") {
email.style.border = "solid 1px red"
document.getElementById("lblemail").style.visibility="visible";
return false;
} else {
return true; }

You should add event listener on input event:
const email = document.getElementById('email');
const label = document.getElementById('lblemail');
email.addEventListener('input', function(e) {
if (!e.target.value.trim()) {
email.style.border = 'solid 1px red';
label.style.visibility = 'visible';
} else {
email.style.border = 'solid 1px black';
label.style.visibility = 'hidden';
}
})
It's better to use input event because it checks input each time you change it

I think you can unset using js code
var email = document.getElementById("email");
if (email.value.trim() == "") {
email.style.border = "solid 1px red"
document.getElementById("lblemail").style.visibility="visible";
return false;
} else {
email.style.border = "none"
document.getElementById("lblemail").style.visibility="hidden";
return true;
}

i think you can use a eventlistener, this should work
var email = document.getElementById("email");
email.addEventListener('change', () => {
if (email.value.trim() == "") {
email.style.border = "solid 1px red"
document.getElementById("lblemail").style.visibility="visible";
return false;
} else {
email.style.border = none;
document.getElementById("lblemail").style.visibility="visible";
return true; }
})

Related

How should I include these functions in AllValidate function?

When click on the submit button, I want to make sure it can detect if the user correctly entered the forms through the functions below, if user did not enter correctly it can stop the form from being submit.
What should I include in my AllValidate function?*
<button name="regbtn" id="register_btn" class="reg_btn" type="submit" onclick="AllValidate()">Register</button>
function addressValidate()
{
var address = document.getElementById("reg_add").value;
var space = /^\s*$/;
var flag = true;
if(address.match(space))
{
document.getElementById("add_error").innerHTML = "Address is required.";
document.getElementById("reg_add").style.border = "2px solid red";
flag = true;
}
else
{
document.getElementById("add_error").innerHTML = "";
document.getElementById("reg_add").style.border = "2px solid #f0f0f0";
flag = false;
}
return flag;
}
function phoneValidate()
{
var phoneNo = document.getElementById("reg_phone").value;
var pattern = /[0-9]{3}-[0-9]{4}-[0-9]{4}/;
var space = /^\s*$/;
var flag = true;
if(phoneNo.match(space))
{
document.getElementById("phone_error").innerHTML = "Phone number is required.";
document.getElementById("reg_phone").style.border = "2px solid red";
flag = true;
}
else if(phoneNo.match(pattern))
{
document.getElementById("phone_error").innerHTML = "";
document.getElementById("reg_phone").style.border = "2px solid #f0f0f0";
flag = false;
}
else
{
document.getElementById("phone_error").innerHTML = "Please enter a valid phone number.";
document.getElementById("reg_phone").style.border = "2px solid red";
flag = true;
}
return flag;
}
AllValidate()
{
}
First you have to edit the submit button as follows
<button name="regbtn" id="register_btn" class="reg_btn" type="submit" onclick="return AllValidate()">Register</button>
Then your AllValidate() function follows
function AllValidate(){
return (addressValidate() && phoneValidate());
}
use that way, with HTML5 auto validation
use attribute required
use attribute pattern ( you can also use input type="tel")
sample code
// personnalize your error message
const myForm = document.forms['my-form']
myForm.reg_phone.oninvalid=_=>
{
let msg = (myForm.reg_phone.value.trim() === '')
? 'Phone number is required.'
: 'Please enter a valid phone number.'
myForm.reg_phone.setCustomValidity(msg)
}
// just to verify input...
myForm.onsubmit = evt =>
{
evt.preventDefault() // just for test here (disable submit)
// shwo values
console.clear()
console.log( 'name :' , myForm.reg_name.value )
console.log( 'address :' , myForm.reg_add.value )
console.log( 'Phone :' , myForm.reg_phone.value )
}
form {
display: flex;
flex-direction: column;
width: 18em;
}
label {
display: block;
margin-top: .7em;
}
label * {
vertical-align: baseline;
}
label input,
label textarea {
display: block;
float: right;
font-size:1.2em;
padding: .2em;
}
label input {
width: 9em;
}
button {
margin: 2em;
font-weight: bold;
}
<form action="..." name="my-form">
<label>
name :
<input type="text" name="reg_name" required>
</label>
<label>
address :
<textarea name="reg_add" rows="4" required placeholder="address"></textarea>
</label>
<label>
Phone :
<input type="text" name="reg_phone" required pattern="\d{3}-\d{4}-\d{4}" placeholder="___-____-____">
</label>
<button type="submit">Register</button>
</form>

How to have all errors pointed out instead of one by one

Here's the cobbled script. It works as in the minute you leave something blank, it points it out via the submit button. But it's annoying because it points it out one by one instead of right away all fields that are blank.
How do I fix this? Please break it down in bite-size as the bigger goal here is understanding it not just merely making this work.
document.forms[0].onsubmit= function() {
var form = document.forms[0];
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].value.length == 0) {
console.log(form.elements[i]);
form.elements[i].border = "1px solid red";
form.elements[i].style.backgroundColor = "#FFCCCC";
return false;
}
}
}
<form method="post" action="" id="myForm">
<div id="validation"></div>
<p><label>Name<br><input type="text" name="Name"></label></p>
<p><label>Email<br><input type="email" name="Email" ></label></p>
<p><input type="submit" value="Submit"></p>
</form>
Your return statement is causing the loop to halt early. Just let it run to the end if you want to signal all incomplete fields.
document.forms[0].onsubmit= function(event) {
for (var i = 0; i < this.elements.length; i++) {
if (this.elements[i].value.length == 0) {
event.preventDefault();
this.elements[i].style.border = "1px solid red";
this.elements[i].style.backgroundColor = "#FFCCCC";
}
}
}
And here's a more modern way to write it, using a class and newer syntax.
document.querySelector("form").addEventListener("submit", function(event) {
for (const el of this.elements) {
if (el.classList.toggle("incomplete", el.value.length == 0)) {
event.preventDefault();
}
}
});
.incomplete {
border: 1px solid red;
background-color: #FFCCCC;
}
<form method="post" action="" id="myForm">
<div id="validation"></div>
<p><label>Name<br><input type="text" name="Name"></label></p>
<p><label>Email<br><input type="email" name="Email" ></label></p>
<p><input type="submit" value="Submit"></p>
</form>
You exit the loop as soon as an input element of the form has a length of 0 :
if (form.elements[i].value.length == 0) {
.. ..
return false;
}
The return false; must be located after the loop if at least an input didin't match to your requirements.
You may use a boolean variable to store this information.
<script>
document.forms[0].onsubmit= function() {
var form = document.forms[0];
var hasError = false;
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].value.length == 0) {
console.log(form.elements[i]);
form.elements[i].border = "1px solid red";
form.elements[i].style.backgroundColor = "#FFCCCC";
hasError = true;
}
}
if (hasError){
return false;
}
}
</script>

Issue with validation of a form on submit?

I have a problem with my code. It is not working correctly. When you start filling the form you fill your name, then you fill phone. If you click with mouse the form is not submitted until you click somewhere else before clicking the submit button or click twice on submit button or press ENTER. Why this happens?
I want that after fill in the last field I can click mouse on submit and it will work.
//validation name
document.myform.name.onchange= function() {
var name = document.myform.name.value;
if (name === "") {
document.myform.name.removeAttribute("class", "ready");
document.myform.name.style.border = "1px solid #da3637";
document.getElementById("Error").style.display = "block";
document.getElementById("ErrorTwo").style.display = "none";
} else {
document.myform.name.style.border = "1px solid #509d12";
document.getElementById("Error").style.display = "none";
var pattern = new RegExp("^[а-я]+$", "i");
var isValid = this.value.search(pattern) >= 0;
if (!(isValid)) {
document.myform.name.style.border = "1px solid #da3637";
document.getElementById("ErrorTwo").style.display = "block";
document.myform.name.removeAttribute("class", "ready");
} else {
document.getElementById("ErrorTwo").style.display = "none";
document.myform.name.style.border = "1px solid #509d12";
document.myform.name.setAttribute("class", "ready");
}
}
};
//validation phone
document.myform.phone.onchange = function() {
var name = document.myform.phone.value;
if (name === "") {
document.myform.phone.removeAttribute("class", "ready");
document.myform.phone.style.border = "1px solid #da3637";
document.getElementById("telError").style.display = "block";
document.getElementById("telErrorTwo").style.display = "none";
} else {
document.myform.phone.style.border = "1px solid #509d12";
document.getElementById("telError").style.display = "none";
var pattern = new RegExp("[- +()0-9]+");
var isValid = this.value.search(pattern) >= 0;
if (!(isValid)) {
document.myform.phone.style.border = "1px solid #da3637";
document.getElementById("telErrorTwo").style.display = "block";
} else {
document.getElementById("telErrorTwo").style.display = "none";
document.myform.phone.style.border = "1px solid #509d12";
document.myform.phone.setAttribute("class", "ready");
}
}
};
//filling the form
document.myform.onchange = function() {
var a = document.myform.name.getAttribute("class");
var c = document.myform.phone.getAttribute("class");
if (a === "ready" && c === "ready") {
document.getElementById("save").removeAttribute("disabled");
document.getElementById("save").style.cursor = "pointer";
document.getElementById("save").style.opacity = "1";
}
};
$(".callback-submit").click(function() {
var url = "send.php";
$.ajax({
type: "POST",
url: url,
data: $("#callForm form").serialize(),
success: function(data)
{
var name = $("input[name=name]").val("");
var rel= $("input[name=phone]").val("");
$("#flipTwo").addClass("animateTwo");
}
});
return false; // avoid to execute the actual submit of the form.
});
html:
<div class="callback-form" id="callForm">
<form name='myform'>
<span class="close-btn" id="close">✖</span>
<p>Введите свои контактные данные</p>
<p>Мы Вам перезвоним</p>
<input type="text" name="name" placeholder="Имя" maxlength="30">
<p class="Error" id="Error">Это поле обязательное для заполнения</p>
<p class="ErrorTwo" id="ErrorTwo">Некорректный ввод</p>
<input type="tel" name="phone" placeholder="Телефон" maxlength="20" minlength="7">
<p class="Error" id="telError">Это поле обязательное для заполнения</p>
<p class="ErrorTwo" id="telErrorTwo">Некорректный ввод</p>
<div id="flipTwo">
<input class="callback-submit" type="submit" value="Отправить заявку" name="save" id="save" disabled>
<span id="iconCheckTwo">Отправлено<i class="fa fa-check" aria-hidden="true"></i></span>
</div>
<p>Данные не передаються третьим лицам</p>
</form>
</div>
I think you can make it in more organised way, First make little clean up on your html code
like: `
Введите свои контактные данные
Мы Вам перезвоним
Это поле обязательное для заполнения
Некорректный ввод
Это поле обязательное для заполнения
Некорректный ввод
<div class="group">
<div id="flipTwo">
<input class="callback-submit" type="submit" value="Отправить subtmi" name="save" id="save">
<span id="iconCheckTwo">Отправлено<i class="fa fa-check" aria-hidden="true"></i></span>
</div>
</div>
<p>Данные не передаються третьим лицам</p>
</form>`
And then write clean code for your jQuery and structured. I did partial and I hope you can complete your rest:
jQuery(document).ready(function($) {
$('#myform').on('submit', function(){
var form = this;
if(validateForm(form)) {
var values = $(form).serialize();
var url = "send.php";
$.ajax({
url: url,
type: "post",
data: values ,
success: function (data) {
var name = $("input[name=name]").val("");
var rel= $("input[name=phone]").val("");
$("#flipTwo").addClass("animateTwo");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
event.preventDefault(); //changed to allow the tag manager to notice that the form was submitted
}
else{
event.preventDefault();
return false;
}
});
// validate Form
function validateForm(form) {
valid = true;
$(form).find('input[type=text], input[type=email]').each(function(i, val){
if(validateField(val, true) == false) { valid = false; }
});
return valid;
}
// validate all form fields
function validateField(field, submit) {
var val = $(field).val();
if(submit){
// you can more specific
if($(field).attr('name') == 'name' && val == '') {
$(field).parent().find('#Error').show();
$(field).parent().find('#ErrorTwo').hide();
return false; }
else if (!isValidName(val)){
// your next rule
return false;
}
// same way for email
if($(field).attr('type') == 'email') {
$(field).parent().addClass('error');
return false; }
else if (!isValidName(val)){
// your next rule
return false;
}
}
}
function isValidName(name) {
var pattern = new RegExp(/^[а-я]+$/);
return pattern.test(no);
}
function isValidPhone(no) {
var pattern = new RegExp(/[- +()0-9]+/);
return pattern.test(no);
}
// Run validation before Submit the form
$('input[type=text], input[type=email]').on('change', function(){
if($(this).val() != ''){
$(this).parent().removeClass('error valid');
validateField(this, false);
}
});
});
JSfiddle: https://jsfiddle.net/n32c2dwo/4/

javascript Validation: removing the error msg by a textbox

I have a textbox and I used JS to see check if the text box is empty or not.
if it is empty a error message will appear under the text box.
Now when I do go back and enter text into the empty textbox the error message stays. how can I re-check if the user entered any text and then automatically remove the error link.
<label for="last_name_field">Last Name <abbr title="Required">*</abbr></label>
<input type="text" id="last_name_field" name="lastname" placeholder="Last Name" onblur="validateLN()">
function validateLN() {
if (document.form.lastname.value == "") { //create an error message
var msg = " Last Name cannot be blank";
//call the display error function
displayError(document.form.lastname, msg);
}
}
function displayError(element, msg) {
if (element.nextSibling.tagName == "SPAN" && element.nextSibling.textContent.trim == msg.trim) {
return;
} else {
var msgElement = document.createElement("span");
msgElement.textContent = msg;
msgElement.style.color = "red";
element.parentNode.insertBefore(msgElement, element.nextSibling);
element.style.border = "solid 1px red";
}
}
Remove the error from within the onchange event of your textbox.
function validateLN() {
if (document.form.lastname.value == "") { //create an error message
var msg = " Last Name cannot be blank";
//call the display error function
displayError(document.form.lastname, msg);
}
}
document.form.lastname.onchange = function() {
document.getElementById('errorMsg').remove();
}
function displayError(element, msg) {
if (element.nextSibling.tagName == "SPAN" && element.nextSibling.textContent.trim == msg.trim) {
return;
} else {
var msgElement = document.createElement("span");
msgElement.id = 'errorMsg';
msgElement.textContent = msg;
msgElement.style.color = "red";
element.parentNode.insertBefore(msgElement, element.nextSibling);
element.style.border = "solid 1px red";
}
}
Or simply keep it there and toggle its display value:
var msgElement = document.createElement("span");
msgElement.id = 'errorMsg';
msgElement.textContent = msg;
msgElement.style.color = "red";
msgElement.style.display = 'none';
element.parentNode.insertBefore(msgElement, element.nextSibling);
element.style.border = "solid 1px red";
function validateLN() {
if (document.form.lastname.value == "") { //create an error message
var msg = " Last Name cannot be blank";
//call the display error function
document.getElementById('errorMsg').style.display = 'inline';
}
}
document.form.lastname.onchange = function() {
document.getElementById('errorMsg').style.display = 'none';
}

error inner HTML on the wrong place

I have a form validation on 3 required input fields: name, address and city.
I made this javascript:
function Validate(form) {
var error_name = "";
var error_address = "";
var error_city = "";
if (form.name.value.length == 0) {
form.name.style.border = "1px solid red"; /*optioneel */
form.name.style.backgroundColor = "#FFCCCC"; /* optioneel */
error_name = "Name cannot be left blank!";
}
if (form.address.value.length == 0) {
form.address.style.border = "1px solid red"; /*optioneel */
form.address.style.backgroundColor = "#FFCCCC"; /* optioneel */
error_address = "Address cannot be left blank!";
}
if (form.city.value.length == 0) {
form.city.style.border = "1px solid red"; /*optioneel */
form.city.style.backgroundColor = "#FFCCCC"; /* optioneel */
error_city = "City cannot be left blank!";
}
if (error_name.length > 0) {
document.getElementById("error_name").innerHTML = error_name ;
return false;
}
if (error_address.length > 0) {
document.getElementById("error_name").innerHTML = error_address ;
return false;
}
if (error_city.length > 0) {
document.getElementById("error_name").innerHTML = error_city ;
return false;
}
return true;
}
document.getElementById("aanmelden").onsubmit = function () {
return Validate(this);
};
And this is a piece of the form:
<div id="form" >
<h3>Aanmelding WIES Congres</h3>
<p class="legend">Deelnemer</p>
<fieldset class="input2" id="Deelnemer">
<label>Naam:</label>
<div id="error_name"></div>
<input type="text" name="name" maxlength="25" size="25">
<label class="right">Bedrijf:</label>
<input class="right" type="text" name="company" maxlength="25" size="25">
<br/>
<label>Adres:</label>
<div id="error_address"></div>
<input type="text" name="address" maxlength="25" size="25"> <br />
<label>Postcode:</label>
<input type="text" name="postalcode" maxlength="6" size="6"> <br />
<label class="right">Plaats:</label>
<div id="error_city"></div>
<input class="right" type="text" name="city" maxlength="25" size="25">
<label>Land</label>
<select name="country">
and so on----
As you can see in the form, the name error should occur above the name field, the address error above the address field and so on..
But this is not happening: all errors are shown above the name field, wether it is name, address or city error...
What do i do wrong?
It looks like all of your errors are targeting the same div : #error_name.
Try changing each one to target the appropriate div:
document.getElementById("error_name").innerHTML = error_name;
document.getElementById("error_address").innerHTML = error_address;
document.getElementById("error_city").innerHTML = error_city;
Also, some of your input names do not match their references. For example:
form.name should be form.form_name
form.address should be form.form_address
form.city should be form.form_city
In order to display all the errors at once (instead of just one per form submission) you'll need to remove all the return false; lines and put one conditional return at the end of the function. Also, you'll need a way to "clear" the errors after the user corrects blank inputs.
Here is the restructured function:
function Validate(form) {
// INITIALIZE VARIABLES
var error_name = "";
var error_address = "";
var error_city = "";
var valid = true;
// CHECK FOR BLANK INPUTS, SET ERROR MESSAGES
if (form.form_name.value.length == 0) {
error_name += "Name cannot be left blank!";
}
if (form.form_address.value.length == 0) {
error_address += "Address cannot be left blank!";
}
if (form.form_city.value.length == 0) {
error_city += "City cannot be left blank!";
}
// UPDATE ERROR MESSAGE DISPLAYS
document.getElementById("error_name").innerHTML = error_name;
document.getElementById("error_address").innerHTML = error_address;
document.getElementById("error_city").innerHTML = error_city;
// IF ERROR MESSAGE EXISTS, CHANGE STYLES AND SET VALID TO FALSE
// ELSE IF NO ERRORS, RESET STYLES
if (error_name.length > 0) {
form.form_name.style.border = "1px solid red";
form.form_name.style.backgroundColor = "#FFCCCC";
valid = false;
} else {
form.form_name.style.border = "none";
form.form_name.style.backgroundColor = "#FFFFFF";
}
if (error_address.length > 0) {
form.form_address.style.border = "1px solid red";
form.form_address.style.backgroundColor = "#FFCCCC";
valid = false;
} else {
form.form_address.style.border = "none";
form.form_address.style.backgroundColor = "#FFFFFF";
}
if (error_city.length > 0) {
form.form_city.style.border = "1px solid red";
form.form_city.style.backgroundColor = "#FFCCCC";
valid = false;
} else {
form.form_city.style.border = "none";
form.form_city.style.backgroundColor = "#FFFFFF";
}
// RETURN FORM VALIDITY (TRUE OR FALSE)
// "FALSE" STOPS THE FORM FROM SUBMITTING
return valid;
}
// CONFIGURE ONSUBMIT FUNCTION
document.getElementById("aanmelden").onsubmit = function () {
return Validate(this);
};
Here is a working example (jsfiddle).

Categories