How to display all errors on submit with javascript - javascript

I will like to know how can I display all of my validated errors at once when user submit a form. Until here, it works fine but it shows the errors one by one.
const form = document.getElementsByTagName('form')[0];
let errorMessages = [
"please fill in your name here",
"please, fill in your email correct here",
];
const reg = /^\d+$/;
form.addEventListener('submit', function(e){
if(valName.value !== ''){
valName.nextElementSibling.textContent = '';
valName.className = '';
} else {
e.preventDefault();
valName.nextElementSibling.textContent = errorMessages[0];
valName.className = 'errorborder';
return false;
}
if(valEmail.value.indexOf('#') != -1 && this.value.indexOf('.') != -1){
valEmail.nextElementSibling.textContent = '';
valEmail.className = '';
} else {
e.preventDefault();
valEmail.nextElementSibling.textContent = errorMessages[1];
valEmail.className = 'errorborder';
return false;
}
});
many thanks in advance!

You have to remove your returns - otherwise the code will stop there.
I have also moved codes into functions instead of copying.
const form = document.getElementsByTagName('form')[0];
let errorMessages = [
"please fill in your name here",
"please, fill in your email correct here",
];
const reg = /^\d+$/;
function isEmailValid(email){
return email.indexOf('#') != -1 && email.indexOf('.') != -1;
}
function isNameValid(name){
return name !== ''
}
function setErrorMessage(el, errorMessage){
el.nextElementSibling.textContent = errorMessage;
el.className = 'errorborder';
}
function clearError(el){
el.nextElementSibling.textContent = '';
el.className = '';
}
form.addEventListener('submit', function(e){
var validName = isNameValid(valName.value);
var validEmail = isEmailValid(valEmail.value);
if(!validName){
setErrorMessage(valName, errorMessages[0]);
}else{
clearError(valName);
}
if(!validEmail){
setErrorMessage(valEmail, errorMessages[1]);
}else{
clearError(valEmail);
}
if(!validName || !validEmail) {
e.preventDefault();
return false;
}
})

You can store all the errors in a string variable and display all of them at once.
form.addEventListener('submit', function(e){
var errors = "";
if(valName.value !== ''){
valName.nextElementSibling.textContent = '';
valName.className = '';
}
else{
e.preventDefault();
errors += errorMessages[0];
}
if(valEmail.value.indexOf('#') != -1 && this.value.indexOf('.') != -1){
valEmail.nextElementSibling.textContent = '';
valEmail.className = '';
}else{
e.preventDefault();
errors += errorMessages[1];
}
if(errors !== ""){
valName.className = 'errorborder';
valName.nextElementSibling.textContent = errors.
return false;
}
})

Related

Where to put e.preventDefault() in my javascript validation?

I've spent the past few days trying to figure this out without success. I'm wanting to only preventdefault if it fails. I'm assuming the form wont submit because it's preventdefault either way. Thanks.
form.addEventListener("submit", (e)=>{
e.preventDefault();
engine(username, 0, "Name cannot be blank");
engine(email, 1, "Email cannot be blank");
engine(message, 2, "Message cannot be blank");
})
let engine = (id, serial, message) =>{
if(id.value.trim() === ""){
errorMsg[serial].innerHTML = message;
faulureIcon[serial].style.opaity = "1";
successIcon[serial].style.opacity = "0";
}
else{
errorMsg[serial].innerHTML = "";
faulureIcon[serial].style.opacity = "0"
successIcon[serial].style.opacity = "1";
}
You need to make your function return a flag to indicate whether it succeeded or not, and then use that flag in your event handler, for example:
form.addEventListener("submit", (e) => {
let valid = true;
valid &&= engine(username, 0, "Name cannot be blank");
valid &&= engine(email, 1, "Email cannot be blank");
valid &&= engine(message, 2, "Message cannot be blank");
if (!valid) {
e.preventDefault();
}
});
const engine = (id, serial, message) => {
if (id.value.trim() === "") {
errorMsg[serial].innerHTML = message;
faulureIcon[serial].style.opacity = "1"; // Fixed typo on this line
successIcon[serial].style.opacity = "0";
return false;
}
errorMsg[serial].innerHTML = "";
faulureIcon[serial].style.opacity = "0";
successIcon[serial].style.opacity = "1";
return true;
};
I've used &&= there because it makes sense to show all the invalid things rather than just the first, which is what you'd get if you just did const valid = engine(/*...*/) && engine(/*...*/) && engine(/*...*/);.
So, make the validation function engine to return a flag true if valid and false if not valid, and use every method to check that all are valid.
form.addEventListener("submit", (e)=>{
const valid = [engine(username, 0, "Name cannot be blank"),
engine(email, 1, "Email cannot be blank"),
engine(message, 2, "Message cannot be blank")].every(v => v)
if (!valid) {
e.preventDefault();
}
})
let engine = (id, serial, message) =>{
if(id.value.trim() === ""){
errorMsg[serial].innerHTML = message;
faulureIcon[serial].style.opaity = "1";
successIcon[serial].style.opacity = "0";
return false;
} else {
errorMsg[serial].innerHTML = "";
faulureIcon[serial].style.opacity = "0"
successIcon[serial].style.opacity = "1";
return true;
}

email validation with javascript - if text box is empty i will print a message, how can i use my function to make sure the email is correct?

This is the code i have so far:
i have set up the function to detect the input is a valid email input.
i have set up the code to print an error message when there is no input.
No message is needed if email is correct, only when email is invalid.
"use strict";
function validEmail(email) {
var re =
/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.
[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate() {
var errorMsg = "";
var emailboxInput = document.getElementById("email");
var emailbox = emailboxInput.value.trim();
emailboxInput.value = emailbox;
if (emailbox === "") {
errormsg += "Email cannot be empty.<br>";
}
if (emailbox === (!validEmail(email))
{
}
else {
errorMessage += "Provide a valid email address<br>";
}
else {
errorMsg += "Provide a valid email address<br>";
}
return errorMsg;
}
// submit button
// msg = html area where error messages are displayed
var sendBtn = document.getElementById("form-send");
sendBtn.onclick = function () {
var msgArea = document.getElementById("msg");
var msg = validate();
if (msg === "") {
return true;
} else {
msgArea.innerHTML = msg;
return false;
}
};

Login Validation Javascript

require the user to enter a username that is 3 or more alphanumeric characters.
o require the user to enter a password that is 8 or more characters.
I am working on a login form, I have create html, css, and javascript files. I have created the validation functions but when I load my html I don't see the validation messages.
var subButton = document.getElementById('submit', validation);
function validation(e) {
let data = {};
e.preventDefault();
console.log(e);
errors.forEach(function (item) {
item.classList.add("hide");
})
let error = false;
inputs.forEach(function (el) {
let tempName = el.getAttribute("userName");
if (tempName != null) {
el.style.borderColor = "#ddd";
if (el.value.length == 0 && required.includes(tempName)) {
addError(el, "Required Field", tempName);
error = true;
}
if (tempName == "email") {
let exp = /([A-Za-z0-9._-]+#[A-Za-z0-9._-]+\.[A-Za-z0-9]+)\w+/;
let result = exp.test(el.value);
if (!result) {
addError(el, "Invalid Email", tempName);
error = true;
}
}
if (tempName == "password") {
let exp = /[A-Za-z0-9]+$/;
let result = exp.test(el.value);
if (!result) {
addError(el, "Only numbers and Letters", tempName);
error = true;
}
if (!(el.value.length > 8)) {
addError(el, "Needs to be greater than 8 characters", tempName);
error = true;
}
}
data[tempName] = el.value;
}
})
}
function addError(el, mes, fieldName) {
let temp = el.nextElementSibling;
temp.classList.remove("hide");
temp.textContent = fieldName.toUpperCase() + " " + mes;
el.login.borderColor = "red";
el.focus();
}
I don't see the validation alerts

Javascript is partially working and isn't returning an answer

My javascript code is partially working, it works on the first name validation, on the Email validation it shows the error for a second but it doesn't return false and the password validation isn't working at all.
function validate() {
var emailOk = validateEmail();
var fNameOk = validateFirstName();
var paswOk = validatePassword();
return fNameOk;
return paswOk;
return emailOk;
}
function validatePassword() {
var name = document.getElementById("psw");
name.style.borderColor = "";
document.getElementById("passwordErr").innerText = "";
if (name.value.length < 7) {
name.style.borderColor = "red";
var error = document.getElementById("passwordErr");
error.innerText = "Password does not fit the criteria.";
return false;
}
else
return true;
}
function validateFirstName() {
var name = document.getElementById("F_Name");
name.style.borderColor = "";
document.getElementById("fNameErr").innerText = "";
if (name.value.length == 0) {
name.style.borderColor = "red";
var error = document.getElementById("fNameErr");
error.innerText = "Missing first name.";
return false;
}
else
return true;
}
function validateEmail() {
var name = document.getElementById("email");
name.style.borderColor = "";
document.getElementById("emailErr").innerText = "";
var re = /\S+#\S+\.\S+/;
if (re.test(name) == true)
return true;
else
var error = document.getElementById("emailErr");
error.innerText = "Not a vaild email.";
return false;
}
I expect it to stop when you enter a password that is shorter than 7 and for it to show the message. I also expect it to stop when The email is invalid.
You are writing your else statements incorrectly. They should also be opened and closed with curly brackets
else { // code }
Also, code written after a return statement will not be executed. You will need to return 3 variables at the same time, using an object or array.
function validate() {
var emailOk = validateEmail();
var fNameOk = validateFirstName();
var paswOk = validatePassword();
console.log(fNameOk, paswOk, emailOk)
return {
fNameOk,
paswOk,
emailOk
}
}
function validatePassword() {
var name = document.getElementById("psw");
name.style.borderColor = "";
document.getElementById("passwordErr").innerText = "";
if (name.value.length < 7) {
name.style.borderColor = "red";
var error = document.getElementById("passwordErr");
error.innerText = "Password does not fit the criteria.";
return false;
} else {
return true;
}
}
function validateFirstName() {
var name = document.getElementById("F_Name");
name.style.borderColor = "";
document.getElementById("fNameErr").innerText = "";
if (name.value.length == 0) {
name.style.borderColor = "red";
var error = document.getElementById("fNameErr");
error.innerText = "Missing first name.";
return false;
} else {
return true;
}
}
function validateEmail() {
var name = document.getElementById("email");
name.style.borderColor = "";
document.getElementById("emailErr").innerText = "";
var re = /\S+#\S+\.\S+/;
if (re.test(name) == true) {
return true;
} else {
var error = document.getElementById("emailErr");
error.innerText = "Not a vaild email.";
return false;
}
}
<input id="email" placeholder="Email" /><br>
<input id="F_Name" placeholder="First Name" /><br>
<input id="psw" type="password" placeholder="Password" /><br>
<button onclick="validate()">Register</button>
<div id="passwordErr"></div>
<div id="fNameErr"></div>
<div id="emailErr"></div>
One thing I can say, use:
return fNameOk && paswOk && emailOk;
instead of:
return fNameOk;
return paswOk;
return emailOk;
Because when you write "return fNameOk;", it will return from the function. The next two lines will never be executed.

Validating using JavaScript - how to show to all validation error message's

I have function that checks if fields are blank but if all fields are blank it only shows one of the validation message's, I think this is because I have used an if statement:
function validateForm()
{
var sName=document.forms["myForm"]["surname_5"].value;
if (sName==null || sName=="")
{
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
return false;
}
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("fNameMessage").innerHTML = "*First name is required";
return false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("titleMessage").innerHTML = "You need to select a title";
return false;
}
}
How do I get it so all validation messages show if the user has left all fields blank?
Don't return false immediately. Set a variable to false (after defining it as true at the very start of the function) and return that variable at the end.
Try something like this (or add all your code if you need more details)
JavaScript:
function validateForm() {
var sName = document.forms["myForm"]["surname_5"].value;
var ret = true;
if (sName == null || sName == "") {
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
ret = false;
}
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "*First name is required";
ret = false;
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
ret = false;
}
return ret;
}

Categories

Resources