JavaScript - How to hide errors on Form Validation - javascript

How do I hide the error(s) messages and the red border when a user corrects their errors on my form? At the moment it will keep showing the error(s) until the page is refreshed or submitted.
function checkForm() {
var valid = true;
if (!retext.test(document.myform.textfield.value)) {
document.myform.textfield.style.border = "3.5px solid red";
document.getElementById("text").innerHTML = "Invalid text.";
document.getElementById("text").style.display = "block";
valid = false;
}
if (!re.test(document.myform.email.value)) {
document.myform.email.style.border = "3.5px solid red";
document.getElementById("emailwarn").innerHTML = "Invalid email.";
document.getElementById("emailwarn").style.display = "block";
valid = false;
}
if (!retel.test(document.myform.tel.value)) {
document.myform.tel.style.border = "3.5px solid red";
document.getElementById("telwarn").innerHTML = "Invalid telephone number.";
document.getElementById("telwarn").style.display = "block";
valid = false;
}
return valid;
}
I really have no idea on how to do this.

Assuming the checkForm function is called each time the form is amended you can include else clauses to reset the style and visible state of the warnings
function checkForm() {
var valid = true;
if (!retext.test(document.myform.textfield.value)) {
document.myform.textfield.border = "3.5px solid red";
document.getElementById("text").innerHTML = "Invalid text.";
document.getElementById("text").style.display = "block";
valid = false;
} else {
document.myform.textfield.border = 0;
document.getElementById("text").style.display = "none";
}
if (!re.test(document.myform.email.value)) {
document.myform.email.style.border = "3.5px solid red";
document.getElementById("emailwarn").innerHTML = "Invalid email.";
document.getElementById("emailwarn").style.display = "block";
valid = false;
} else {
document.myform.email.border = 0;
document.getElementById("emailwarn").style.display = "none";
}
if (!retel.test(document.myform.tel.value)) {
document.myform.tel.style.border = "3.5px solid red";
document.getElementById("telwarn").innerHTML = "Invalid telephone number.";
document.getElementById("telwarn").style.display = "block";
valid = false;
} else {
document.myform.tel.border = 0;
document.getElementById("telwarn").style.display = "none";
}
return valid;
}

Just add code which clears up the error messages at the beginning of your checkForm() function.
In your current code if error messages had been set once they have no chance to be changed on the correct input.
For example,
function clearErrors() {
document.getElementById("text").style.display = "none";
document.getElementById("emailwarn").style.display = "none";
document.getElementById("telwarn").style.display = "none";
}
function checkForm() {
var valid = true;
clearErrors();
...

Well first it would be better to seperate javascript and CSS styles, by applying classes:
input.error {
border: 3.5px solid red;
}
To apply the style:
document.myform.textfield.classList.add("error");
To remove the style:
document.myform.textfield.classList.remove("error");
To hide the warn element use:
document.getElementById("telwarn").style.display = "none";
Beware that classList does not work with ie < 10

Related

How to make a loop wait for an event listener?

I am trying to create a coin toss game where you set the number of games you want to play, and then choose head or tails for each iteration. But my for loop doesen't wait for the eventListener and the loop is over before the user even clicked once.
function play(){
head.addEventListener("click", choice);
tails.addEventListener("click", choice);
}
function choice(e){
let random = Math.floor(Math.random() *2);
console.log(random);
let clicked = e.target;
e.target.style.border = "3px solid green";
head.removeEventListener("click", choice);
tails.removeEventListener("click", choice);
if (random == 0){
result.src = head.src;
result.style.height = "100%";
if(result.src == clicked.src){
result.style.border = "3px solid green";
}
else{
result.style.border = "3px solid red";
}
}
if (random == 1){
result.src = tails.src;
result.style.height = "100%";
if(result.src == clicked.src){
result.style.border = "3px solid green";
}
else{
result.style.border = "3px solid red";
}
}
setTimeout(refresh, 3000);
function refresh(){
result.style.border = "none";
clicked.style.border = "none";
}
}
function wait(){
for (let i = 0; i < playAmount; i++){
console.log(i);
play();
}
}
wait();
Thank you in advance!
You can solve this problem without for loop.
Just take a variable count = 0 and flag = false at the starting .
Now just follow the program as under
var count = 0 , flag = true ;
flag&&head.addEventListener("click", choice);
flag&&tails.addEventListener("click", choice);
function choice(e){
if(count>=playAmount)flag=false;
else count++;
let random = Math.floor(Math.random() *2);
console.log(random);
let clicked = e.target;
e.target.style.border = "3px solid green";
head.removeEventListener("click", choice);
tails.removeEventListener("click", choice);
if (random == 0){
result.src = head.src;
result.style.height = "100%";
if(result.src == clicked.src){
result.style.border = "3px solid green";
}
else{
result.style.border = "3px solid red";
}
}
if (random == 1){
result.src = tails.src;
result.style.height = "100%";
if(result.src == clicked.src){
result.style.border = "3px solid green";
}
else{
result.style.border = "3px solid red";
}
}
setTimeout(refresh, 3000);
function refresh(){
result.style.border = "none";
clicked.style.border = "none";
}
}
I hope this solves your problem .
Let us go through some key parts of your implementation(refer to my comments inline)
function play() {
head.addEventListener("click", choice);
tails.addEventListener("click", choice);
//the above 2 lines add a click event listener to the two buttons,
//that is, whenever these 2 buttons are clicked,
//the function `choice` will be called
}
function choice(e) {
let random = Math.floor(Math.random() * 2);
console.log(random);
let clicked = e.target;
e.target.style.border = "3px solid green";
head.removeEventListener("click", choice);
tails.removeEventListener("click", choice);
//the above 2 lines remove the click event listener from the two buttons
//that is, now the function `choice` will not be called at button click
if (random == 0) {
result.src = head.src;
result.style.height = "100%";
if (result.src == clicked.src) {
result.style.border = "3px solid green";
} else {
result.style.border = "3px solid red";
}
}
if (random == 1) {
result.src = tails.src;
result.style.height = "100%";
if (result.src == clicked.src) {
result.style.border = "3px solid green";
} else {
result.style.border = "3px solid red";
}
}
setTimeout(refresh, 3000);
function refresh() {
result.style.border = "none";
clicked.style.border = "none";
}
}
function wait() {
for (let i = 0; i < playAmount; i++) {
console.log(i);
play();
//calls the play function `playAmount` times
}
}
wait();
Now let us discuss the problems with this approach
Calling the play() function playAmount times from wait() (tries to) binds(adds) the click event listener to both the buttons playAmount times, but adding the same function n times as an event listener is same as adding it once, reference : addEventListener docs
once choice is called, you remove the event listeners from both the buttons (remember , the event listeners were only bound once in a loop in the wait() function),
now with no event listener bound on the buttons, the buttons wont register the event click anymore.
The below implementation should work for you:
let numberOfTurnsTaken = 0;
//add a global variable to count the turns taken
function play() {
head.addEventListener("click", choice);
tails.addEventListener("click", choice);
//bind the event listeners
}
function choice(e) {
numberOfTurnsTaken++;
//increment the turns
let random = Math.floor(Math.random() * 2);
console.log(random);
let clicked = e.target;
e.target.style.border = "3px solid green";
//remove the event listeners only when the turns are over and we are `handling` the last turn
if(numberOfTurnsTaken == playAmount){
head.removeEventListener("click", choice);
tails.removeEventListener("click", choice);
}
if (random == 0) {
result.src = head.src;
result.style.height = "100%";
if (result.src == clicked.src) {
result.style.border = "3px solid green";
} else {
result.style.border = "3px solid red";
}
}
if (random == 1) {
result.src = tails.src;
result.style.height = "100%";
if (result.src == clicked.src) {
result.style.border = "3px solid green";
} else {
result.style.border = "3px solid red";
}
}
setTimeout(refresh, 3000);
function refresh() {
result.style.border = "none";
clicked.style.border = "none";
}
}
//set things rolling by binding click event handlers on the buttons
play();
//the loop is no longer needed
//function wait() {
// for (let i = 0; i < playAmount; i++) {
// console.log(i);
// play();
// }
//}
//wait();

How can we integrate a "valid email" system in this code?

So now I have my successful code. But what I want to do is include this in my AJAX. So this is my AJAX:
function checkEmail() {
// var myForm = $("#mainForm").serialize();
var fname = $("#first").val();
var lname = $("#second").val();
var email = $("#email").val();
var password = $("#password").val();
var repass = $("#en").val();
if (fname && lname && email && password && repass && password.length >= 6 && password == repass)) {
jQuery.ajax({
url: "connection.php",
data: {
fname:fname,
lname:lname,
email:email,
password:password,
repass:repass
},
type: "POST",
success:function(data){
$("#emailExists").show();
$("#email").css("border","2px solid green");
$("#no").css("visibility","hidden");
$("#yes").css("visibility","visible");
if(data){
$("#email").css("border", "2px solid red");
$("#no").css("visibility","visible");
$("#yes").css("visibility","hidden");
}else
{
$("#email").css("border", "2px solid green");
$("#no").css("visibility","hidden");
$("#yes").css("visibility","visible");
window.location.href = 'home.php';
}
$("#emailExists").html(data);
},
error:function (){
}
});
}
}
So, what I want to do, is basically, in that if statement [if(name && lname...)]. In that particular section, I want to include this particular checking if email valid system too. So I was thinking maybe make this code (the if statement to check if email is valid), into a function, to then add it into the AJAX, so something like this:
if (fname && lname && email && password && repass && password.length >= 6 && password == repass && checkValidateEmail()) {
But if I keep that if statement in a function called checkValiateEmail() and do that, it isn't working. What should I do?
Your error is in line 20 (of my snippet, see below). You are passing your email HTMLElement to the validateEmail() function, not the inputs value. The correct code is the following, you had validateEmail(email).
if(email.value === ""){
// ...
}
else if (!validateEmail(email.value)){ // <- the error was here
// ...
}
else{
// ...
}
The full working code is then:
function validateEmail(email) {
const 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,}))$/;
return re.test(email);
}
const email = document.getElementById("email");
const no = document.getElementById("no");
const yes = document.getElementById("yes");
const mailText = document.getElementById("email-text");
const validEmail = document.getElementById("valid");
email.addEventListener("change", function(){
if(email.value === "") {
no.style.visibility = 'visible';
yes.style.visibility = 'hidden';
email.style.border = '2px solid red';
mailText.style.visibility = 'visible';
mailText.innerText = "Please enter an email address.";
validEmail.style.visibility = 'hidden';
} else if (!validateEmail(email.value)) {
no.style.visibility = 'visible';
yes.style.visibility = 'hidden';
email.style.border = '2px solid red';
mailText.style.visibility = 'hidden';
validEmail.style.visibility = 'visible';
} else {
yes.style.visibility = 'visible';
no.style.visibility = 'hidden';
email.style.border = '2px solid green';
mailText.style.visibility = 'hidden';
}
});
<input type="text" id="email" />
<span id="yes">Yes</span>
<span id="no">No</span>
<span id="valid">Valid</span>
<p id="email-text"></p>

JavaScript: How to display separate error messages when form field is invalid or empty

Im tryin to display one error message when a user submits a form with an invalid email address but display a different error message if the user submits an EMPTY email field.
Somehow I need to change the email error message when the form is submitted.
const invalidEmail = document.createElement('span');
invalidEmail.className = "error";
invalidEmail.id = "invalidEmail";
invalidEmail.textContent = "Please enter a valid Email";
//////////////////////////////////////////////////////
const emptyEmail = document.createElement('span');
emptyEmail.className = "error";
emptyEmail.id = "emptyEmail";
emptyEmail.textContent = "Email is required";
//////////////////////////////////////////////////////
function validateEmail() {
// get value from email input
const email = $("#mail").val();
const regexEmail = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (regexEmail.test(email)) {
return true;
} else if (email === "") {
alert('enter email');
return false;
}
}
$("#mail").keyup(function() {
if (emptyEmail()) {
// if the user email is valid set the input text and border to red
email.style.border = "2px solid green";
emptyEmail.style.display = "none";
return true;
} else {
// if the user email is not valid set the input text and border to red
email.before(emptyEmail);
emptyEmail.style.fontSize = "1em"
emptyEmail.style.color = "red";
email.style.border = "2px solid red";
emptyEmail.style.display = "block";
return false;
}
});
$("#mail").keyup(function() {
if (validateEmail()) {
// if the user email is valid set the input text and border to red
email.style.border = "2px solid green";
invalidEmail.style.display = "none";
return true;
} else {
// if the user email is not valid set the input text and border to red
email.before(invalidEmail);
invalidEmail.style.fontSize = "1em"
invalidEmail.style.color = "red";
email.style.border = "2px solid red";
invalidEmail.style.display = "block";
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="mail">Email:</label>
<input type="email" id="mail" name="user-email" placeholder="Enter Valid Email">
The following code will do just what you need. I've added the email field within a form and added the submit button just to simulate the situation:
const invalidEmail = document.createElement('span');
invalidEmail.className="error";
invalidEmail.id="invalidEmail";
invalidEmail.textContent="Please enter a valid Email";
//////////////////////////////////////////////////////
const emptyEmail = document.createElement('span');
emptyEmail.className="error";
emptyEmail.id="emptyEmail";
emptyEmail.textContent="Email is required";
//////////////////////////////////////////////////////
function validateEmail(){
// get value from email input
const email = $("#mail").val();
const regexEmail = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if(regexEmail.test(email)){
return true;
} else if (email === "") {
alert('enter email');
return false;
}
}
function isEmptyEmail(obj){
if(obj.val() == '') return true;
else return false;
}
$("form").submit(function(e){
let email = $("#mail");
if(isEmptyEmail(email)){
e.preventDefault();
// if the user email is valid set the input text and border to red
invalidEmail.style.border = "2px solid green";
invalidEmail.style.display = "none";
email.before(emptyEmail);
emptyEmail.style.fontSize = "1em"
emptyEmail.style.color = "red";
emptyEmail.style.border = "2px solid red";
emptyEmail.style.display = "block";
return true;
}else if(!validateEmail()){
e.preventDefault();
// if the user email is valid set the input text and border to red
emptyEmail.style.border = "2px solid green";
emptyEmail.style.display = "none";
email.before(invalidEmail);
invalidEmail.style.fontSize = "1em"
invalidEmail.style.color = "red";
invalidEmail.style.border = "2px solid red";
invalidEmail.style.display = "block";
return true;
} else{
// if the user email is not valid set the input text and border to red
invalidEmail.style.border = "2px solid green";
invalidEmail.style.display = "none";
emptyEmail.style.border = "2px solid green";
emptyEmail.style.display = "none";
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<label for="mail">Email:</label>
<input type="text" id="mail" name="user-email" placeholder="Enter Valid Email">
<input type="submit">
</form>

How to use regular expression for client side verification of entries using javascript?

This javascript code is working until the regular expression is used to evaluate the entries in client side verification through javascript. Please check the regular expressions and get me a solution that can check the entries by checking through regular expressions.
Here I am attaching the code to evaluate. Thanks in advance.
<script type="text/javascript">
var tuname=document.forms["teachersignup"]["tusername"];
var tname=document.forms["teachersignup"]["tname"];
var temail=document.forms["teachersignup"]["temail"];
var tpassword=document.forms["teachersignup"]["tpassword"];
var tiname=document.forms["teachersignup"]["tiname"];
var uname=document.getElementById("uname");
var naame=document.getElementById("nname");
var email=document.getElementById("email");
var pswd=document.getElementById("password");
var iname=document.getElementById("iname");
tuname.addEventListener("blur",unameVerify,true);
tname.addEventListener("blur",nameVerify,true);
temail.addEventListener("blur",emailVerify,true);
tpassword.addEventListener("blur",passwordVerify,true);
tiname.addEventListener("blur",inameVerify,true);
var ck_password = /^[A-Za-z0-9!##$%^&*()_]{8,30}$/;
var ck_iname = /^[A-Za-z0-9 ]*{3,60}$/;
var ck_username = /^[a-zA-Z0-9.\-_#]{3,20}$/;
var ck_name = /^[A-Za-z]{3,60}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
function ValidateForm(){
if(tuname.value == "" ){
tuname.style.border="1px solid red";
uname.innerHTML="Enter a valid username";
tuname.focus();
return false;
}
if(tname.value == "" ){
tname.style.border="1px solid red";
naame.innerHTML="Enter a valid name";
tname.focus();
return false;
}
if(temail.value == "" ){
temail.style.border="1px solid red";
email.innerHTML="Enter a valid email";
temail.focus();
return false;
}
if(tpassword.value == "" ){
tpassword.style.border="1px solid red";
pswd.innerHTML="Enter a valid password";
tuname.focus();
return false;
}
if(tiname.value == "" ){
tiname.style.border="1px solid red";
iname.innerHTML="Enter a valid institute's name";
tuname.focus();
return false;
}
}
function unameVerify(){
if(tuname.value!=""){
tuname.style.border="1px solid #5bc0de";
uname.innerHTML="";
return true;
}
}
function nameVerify(){
if(tname.value!="" ){
tname.style.border="1px solid #5bc0de";
name.innerHTML="";
return true;
}
}
function emailVerify(){
if(temail.value!="" ){
temail.style.border="1px solid #5bc0de";
email.innerHTML="";
return true;
}
}
function passwordVerify(){
if(tpassword.value!=""){
tpassword.style.border="1px solid #5bc0de";
pswd.innerHTML="";
return true;
}
}
function inameVerify(){
if(tiname.value!="" ){
tiname.style.border="1px solid #5bc0de";
iname.innerHTML="";
return true;
}
}
</script>
Try this.
var tuname_val = tuname.value;
var valid_tuname = tuname_val.match(ck_username);
This will return an object having a key 'input' that will store valid input that matched your pattern.
Tell me if this didn't work.

JavaScript: Validate form all at once

When my script validates a filled out form, it will check for errors one at a time rather than for all the errors all at once. I know this is because I'm using if statements which will obviously stop when an argument validates as True.
How do I adapt my script so that it will show the end-user all the errors in one go? Do I use the continue statement? Or is there a better way?
function checkForm() {
if (!retext.test(document.myform.sport.value)) {
document.myform.textfield.style.border = "3.5px solid red";
document.getElementById("text").innerHTML = "Invalid text.";
document.getElementById("text").style.display = "block";
return false;
}
else if (!re.test(document.myform.email.value)) {
document.myform.email.style.border = "3.5px solid red";
document.getElementById("emailwarn").innerHTML = "Invalid email.";
document.getElementById("emailwarn").style.display = "block";
return false;
}
else if (!retel.test(document.myform.tel.value)) {
document.myform.tel.style.border = "3.5px solid red";
document.getElementById("telwarn").innerHTML = "Invalid telephone number.";
document.getElementById("telwarn").style.display = "block";
return false;
}
}
<form name="myform" method="POST" action="http://youtube.com" onsubmit="return checkForm()">
<fieldset>
<legend>Hi</legend>
<label>Random text: </label>
<input type="text" name="textfield">
<div id="text"></div>
<label>Email: </label>
<input type="email" name="email">
<div id="emailwarn"></div>
<label>Tel: </label>
<input type="tel" name="tel" maxlength="11">
<div id="telwarn"></div>
<input type="submit" value="Submit Form">
<input type="reset" value="Reset Form">
</fieldset>
</form>
You need to make the checkForm function run all of the checks, and only have one return (at the end).
eg.
function checkForm() {
var valid = true;
if (!retext.test(document.myform.sport.value)) {
document.myform.textfield.style.border = "3.5px solid red";
document.getElementById("text").innerHTML = "Invalid text.";
document.getElementById("text").style.display = "block";
valid = false;
}
if (!re.test(document.myform.email.value)) {
document.myform.email.style.border = "3.5px solid red";
document.getElementById("emailwarn").innerHTML = "Invalid email.";
document.getElementById("emailwarn").style.display = "block";
valid = false;
}
if (!retel.test(document.myform.tel.value)) {
document.myform.tel.style.border = "3.5px solid red";
document.getElementById("telwarn").innerHTML = "Invalid telephone number.";
document.getElementById("telwarn").style.display = "block";
valid = false;
}
return valid;
}
function checkForm() {
var ok = true;
if (!retext.test(document.myform.sport.value)) {
document.myform.textfield.style.border = "3.5px solid red";
document.getElementById("text").innerHTML = "Invalid text.";
document.getElementById("text").style.display = "block";
ok =false;
}
if (!re.test(document.myform.email.value)) {
document.myform.email.style.border = "3.5px solid red";
document.getElementById("emailwarn").innerHTML = "Invalid email.";
document.getElementById("emailwarn").style.display = "block";
ok =false;
}
if (!retel.test(document.myform.tel.value)) {
document.myform.tel.style.border = "3.5px solid red";
document.getElementById("telwarn").innerHTML = "Invalid telephone number.";
document.getElementById("telwarn").style.display = "block";
ok = false;
}
return ok;
}
Set a return value and return it at the end.
function checkForm() {
var valid = true;
if (!testcondition) {
// do stuff
valid = false;
}
if (!othertestcondition) {
// do stuff
valid = false;
}
return valid;
}

Categories