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

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;
}

Related

e.preventDefault() not letting me submit my form

I wrote some Javascript to validate a form. However, if the form fields pass all validations, the form never submits! Is my code somehow incorrectly preventing the form from being able to submit? If I delete all of the Javascript and use browser's built-in validation then form executes fine and user is added to the database.
const form = document.getElementById('form');
const first_name = document.getElementById('first_name');
const last_name = document.getElementById('last_name');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
// Show input error message
function showError(input, message) {
input.className = 'form-control is-invalid';
const small = input.parentElement.querySelector('small');
small.className = 'invalid-feedback';
small.innerText = message;
}
// Show success outline
function showSuccess(input, message) {
input.className = 'form-control is-valid';
const small = input.parentElement.querySelector('small');
small.className = 'valid-feedback';
small.innerText = message;
}
function checkRequired(inputArray) {
inputArray.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
return false;
} else {
showSuccess(input, "Looks Good!");
return true;
}
});
}
// Check email is valid
function checkEmail(input) {
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,}))$/;
if (re.test(input.value.trim())) {
showSuccess(input, 'Looks Good!');
return true;
} else {
showError(input, 'Email is not valid');
return false;
}
}
// Check input length
function checkLength(input, min, max) {
if (input.value.length < min) {
showError(
input,
`${getFieldName(input)} must be at least ${min} characters`
);
return false;
} else if (input.value.length > max) {
showError(
input,
`${getFieldName(input)} must be less than ${max} characters`
);
return false;
} else {
showSuccess(input, 'Looks Good!');
return true;
}
}
// Check passwords match
function checkPasswordsMatch(input1, input2) {
if (input1.value !== input2.value) {
showError(input2, 'Passwords do not match');
return false;
}
return true;
}
// Get fieldname
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
// Event listeners
form.addEventListener('submit', function(e) {
if (!checkRequired([first_name, last_name, username, email, password, password2])) {
e.preventDefault();
}
if (!checkLength(username, 3, 15)) {
e.preventDefault();
}
if (!checkLength(password, 6, 25)) {
e.preventDefault();
}
if (!checkEmail(email)) {
e.preventDefault();
}
if (!checkPasswordsMatch(password, password2)) {
e.preventDefault();
}
});
Your checkRequired function never returns anything at the moment:
function checkRequired(inputArray) {
inputArray.forEach(function (input) {
if (input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
return false;
} else {
showSuccess(input, "Looks Good!");
return true;
}
});
}
You're returning inside the callback, but the callback ignores its return value (and you still wouldn't want to return true inside the loop, you'd only want to return true after all iterations have finished)
To find the first invalid input, use .find:
function checkRequired(inputArray) {
const invalidInput = inputArray.find(input => input.value.trim() === '');
if (invalidInput) {
showError(input, `${getFieldName(invalidInput)} is required`);
return false;
}
return true;
}
If you want to call showError for every invalid input, then:
function checkRequired(inputArray) {
let valid = true;
for (const input of inputArray) {
if (input.value.trim() === '') {
valid = false;
showError(input, `${getFieldName(input)} is required`);
}
}
return valid;
}
You are not returning anything from checkRequired so it's value will always be false. Although there should be no performance problems, you might be better off using a for loops so that you can break early.
function checkRequired(inputArray) {
for (let input of inputArray) {
if (input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
return false;
}
}
return true;
}

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

How to display all errors on submit with 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;
}
})

How to validate an input as an number in JavaScript

I'm new with JavaScript programming and have been trying to validate a number that is inputted from a user on a php page. Here is the javascript that is included.
var validate_and_create = function(){
var i_number = $("input_number").value;
var isValid = true;
if (i_number === ""){
$("create_n_error").firstChild.nodeValue = "Number text field cannot be blank.";
isValid = false;
} else {
if (typeof i_number === 'number') {
$("create_n_error").firstChild.nodeValue = "This is a number!";
isValid = true;
} else {
$("create_n_error").firstChild.nodeValue = "This is not a number!";
isValid = false;
}
}
It always prints that the input is not a number even when integer values are inserted in the textbox. So I'm sure its taking the input as a string input. So do I have to convert it to integer so I can validate? or am I doing something wrong?
You can use parseInt to convert the value to integer, like parseInt("55", 10) will return 55.
And something like parseInt("xx",10) returns NaN.
Thanks adeneo, isNaN works for validation.
Code below:
var validate_and_create = function(){
var i_number = $("input_number").value;
var isValid = true;
if (i_number === ""){
$("create_n_error").firstChild.nodeValue = "Number text field cannot be blank.";
isValid = false;
} else {
if (isNaN(i_number)) {
$("create_n_error").firstChild.nodeValue = "This is not a number!";
isValid = false;
} else {
$("create_n_error").firstChild.nodeValue = "This is a number!";
isValid = true;
}
}

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