e.preventDefault() not letting me submit my form - javascript

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

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

i want to check the user input in sign up form at runtime not just on clicking the submit button [duplicate]

This question already has answers here:
JavaScript code to stop form submission
(14 answers)
Closed 1 year ago.
I have made a sign up form with validation in username ,name ,password and confirm password all of validations are working on clicking a submit button but I want the validations on run time like if user is entering a password user should see the validations before even clicking submit button
form.addEventListener('submit', e => {
e.preventDefault();
checkInputs();
});
function checkInputs() {
// trim to remove the whitespaces
const usernameValue = username.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
const password2Value = password2.value.trim();
var numbers = /[0-9]/;
var char = /[!##$%^&*()+_{}|]/;
var pwd = /^(?=.*[a-z])/;
var pwd1 = /^(?=.*[A-Z])/;
var pwd2 = /^(?=.*[0-9])/;
if (usernameValue === '') {
setErrorFor(username, 'Username cannot be blank');
}
else {
if (usernameValue.match(numbers) || usernameValue.match(char)) {
setErrorFor(username, 'Username can only contain letters');
} else {
setSuccessFor(username);
}
}
if (emailValue === '') {
setErrorFor(email, 'Email cannot be blank');
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Not a valid email');
} else {
setSuccessFor(email);
}
if (passwordValue === '') {
setErrorFor(password, 'Password cannot be blank');
} else if (passwordValue.length < 8) {
setErrorFor(password, 'Password must a minimum of 8 characters');
}
else if (pwd.test(passwordValue) == false) {
setErrorFor(password,'Password must have 1 lowerCase letter');
}
else if (pwd1.test(passwordValue) == false) {
setErrorFor(password,'Password must have 1 UpperCase letter');
}
else if (pwd2.test(passwordValue) == false) {
setErrorFor(password,'Password must have 1 Number');
}
else {
setSuccessFor(password);
}
if (password2Value === '') {
setErrorFor(password2, 'Password2 cannot be blank');
}
else if (passwordValue !== password2Value) {
setErrorFor(password2, 'Passwords does not match');
} else {
setSuccessFor(password2);
}
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
formControl.className = 'form-control error';
small.innerText = message;
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
please suggest me something how can I make it work on runtime
To check wheather a certain field is valid or not at the time of user input
call your function using oninput event like oninput="return checkInputs()" on input field.

Password validation using javaScript , not working correctly

this is my email address validation using JavaScript, I have only two conditions that work, the one with the special character is not working.
Only the third is tested on the email address, the first two are on the password.
Please help me.
<script type = "text/javascript">
function validateEmail(form) {
var tr = /[A-Za-z0-9]{8,}/
var tr2 = /\S+#\S+\.\S+/
var tr3 = /[A-Za-z0-9]+[a-zA-Z0-9.!$+/?_]/
if (!(tr.test(form.password.value))){
alert("The passowrd length must be more than 8 letters.")
return false;
}
else if (!(tr3.test(form.password.value))){
alert("Enter a special character.")
return false;
}
else if (!(tr2.test(form.email.value))){
alert("Enter a valid email.")
return false;
}
else{
alert("signed in successfully")
window,open("HomePage.html")
return true
}
}
</script>
Just change regex to this.
const form = {
password: {
value: 'buffaloBill3##$',
},
email: {
value: 'hannibal#lecter.com'
}
};
function validateEmail(form) {
var tr = /[A-Za-z0-9]{8,}/
var tr2 = /\S+#\S+\.\S+/
var tr3 = /^(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{0,}$/;
if (!(tr.test(form.password.value))) {
alert("The passowrd length must be more than 8 letters.")
return false;
} else if (!(tr3.test(form.password.value))) {
alert("Enter a special character.")
return false;
} else if (!(tr2.test(form.email.value))) {
alert("Enter a valid email.")
return false;
} else {
alert("signed in successfully")
window, open("HomePage.html")
return true
}
}
validateEmail(form);

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 password validation skip if fields are empty

This works great, but I need it to do is also ignore it if the password field is left blank.
I want the user to be able to update their information without having to change their password. So if they leave the password fields blank, their password remain the same.
document.addEventListener("DOMContentLoaded", function() {
// JavaScript form validation
var checkPassword = function(str)
{
var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$/;
return re.test(str);
};
var checkForm = function(e)
{
if(this.pwd1.value != "" && this.pwd1.value == this.pwd2.value) {
if(!checkPassword(this.pwd1.value)) {
alert("The password you have entered is not valid!");
this.pwd1.focus();
e.preventDefault();
return;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
this.pwd1.focus();
e.preventDefault();
return;
}
};
var add_employee_form = document.getElementById("add_employee_form");
add_employee_form.addEventListener("submit", checkForm, true);
// HTML5 form validation
var supports_input_validity = function()
{
var i = document.createElement("input");
return "setCustomValidity" in i;
}
if(supports_input_validity()) {
var pwd1Input = document.getElementById("field_pwd1");
var pwd1Rule = "Password must contain at least 6 characters, including UPPER/lowercase and numbers.";
pwd1Input.setCustomValidity(pwd1Rule);
var pwd2Input = document.getElementById("field_pwd2");
var pwd2Rule = "Please enter the same Password as above.";
// input onchange event handlers
pwd1Input.addEventListener("change", function() {
this.setCustomValidity(this.validity.patternMismatch ? pwd1Rule : "");
if(this.checkValidity()) {
pwd2Input.pattern = this.value;
pwd2Input.setCustomValidity(pwd2Rule);
} else {
pwd2Input.pattern = this.pattern;
pwd2Input.setCustomValidity("");
}
}, false);
pwd2Input.addEventListener("change", function() {
this.setCustomValidity(this.validity.patternMismatch ? pwd2Rule : "");
}, false);
}
}, false);
</script>
Change your function to have this at the top:
if(!this.pwd1.value) return;
javascript will return false for values of null or blank so this says return if false.
Full function:
var checkForm = function(e)
{
if(!this.pwd1.value) return;
if(this.pwd1.value != "" && this.pwd1.value == this.pwd2.value) {
if(!checkPassword(this.pwd1.value)) {
alert("The password you have entered is not valid!");
this.pwd1.focus();
e.preventDefault();
return;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
this.pwd1.focus();
e.preventDefault();
return;
}
};

Categories

Resources