Login Validation Javascript - 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

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

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

Creating a pattern for a number which must be prefixed by 3 letters eg (IKA111111)

function validatetest(e)
{
debugger;
e.preventDefault();
// Declare all the variables here
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var title = document.getElementById("title").value;
var healthNumber = document.getElementById("healthNumber").value);
var email = document.getElementById("email").value;
var telephoneNumber = parseInt(document.getElementById("telephoneNumber").value);
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
var validText = /^[a-zA-Z]*$/;
var validLastText = /^[a-zA-Z-]*$/;
var validEmail = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]{2,6}$/;
//var n = healthNumber.startsWith("ZHA");
if(firstName!="" && lastName!= "" && title!="" && email !="")
{
if(email.match(validEmail))
{
if(!isNaN(telephoneNumber) && telephoneNumber >= 11111111111 && telephoneNumber <= 99999999999)
{
if(firstName.match(validText) && firstName.length >1)
{
if(lastName.match(validLastText) && lastName.length> 1)
{
if(healthNumber.match(validHealth))
{
alert("All information is Validated");
return true;
}
else
{
alert("error error");
return false;
}
}
else
{
document.getElementById("error4").innerHTML="letters and hypen only";
return false;
}
}
else
{
document.getElementById("error").innerHTML="letters only and more then one character";
return false;
}
}
else
{
document.getElementById("error2").innerHTML="Telephone number must be 11 num digits long";
}
}
else
{
document.getElementById("error3").innerHTML="email is not a valid format ";
return false;
}
}
else
{
alert("All fields must be entered except telephone Number ");
return false;
}
}
i am trying to create a validation process by using a pattern for a user inputted healthnumber so that it validates whether 3 letters are entered followed by 6 numbers via user input. (MIC123456 is example so MIC always has to been entered , those specific letters)
Not sure if my technique is correct by using a pattern stored in the ValidHeath variable as you can i have used this idea for my email validation etc .
You have an extra + in your regex, make it
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
Demo
var isMatch = !!"IKA111111".match(/^[A-Z]{3}[0-9]{6}$/);
isMatch ? console.log( "Matching" ) : console.log( "Not Matching" );

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

Categories

Resources