0% found this document useful (0 votes)
67 views5 pages

HTML Form Validation

The document contains code for form validation in JavaScript. It includes functions to validate a username, email, password, and confirm password on a signup form. Error messages are displayed for invalid fields using the class "error". On valid input, the class is changed to "success". The validation checks length, format, and that passwords match. The code prevents form submission until all fields are valid.

Uploaded by

Soni Soniya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views5 pages

HTML Form Validation

The document contains code for form validation in JavaScript. It includes functions to validate a username, email, password, and confirm password on a signup form. Error messages are displayed for invalid fields using the class "error". On valid input, the class is changed to "success". The validation checks length, format, and that passwords match. The code prevents form submission until all fields are valid.

Uploaded by

Soni Soniya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

loginvalidation.

html

<html>
<head>
<script>
function checkUser()
{
user="abc";
pass="xyz";
us=document.f1.user.value;
ps=document.f1.pass.value;

if(us==user && ps==pass)


{
window.open("TestHome.html");
}
else
{
alert("bye");
}
}
</script>

</head>
<body>
<form action="#" name="f1" onSubmit="checkUser()">
UserName:<input type="text" name="user"><br>
PassWord:<input type="password" name="pass"><br>
<input type="submit">
<a href="signup.html">SignUp</a>
</form>
</body>
</html>

index.html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Form Validation Demo</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<form id="signup" class="form">
<h1>Sign Up</h1>
<div class="form-field">
<label for="username">Username:</label>
<input type="text" name="username" id="username"
autocomplete="off">
<small></small>
</div>

<div class="form-field">
<label for="email">Email:</label>
<input type="text" name="email" id="email" autocomplete="off">
<small></small>
</div>

<div class="form-field">
<label for="password">Password:</label>
<input type="password" name="password" id="password"
autocomplete="off">
<small></small>
</div>

<div class="form-field">
<label for="confirm-password">Confirm Password:</label>
<input type="password" name="confirm-password" id="confirm-
password" autocomplete="off">
<small></small>
</div>

<div class="form-field">
<input type="submit" value="Sign Up">
</div>
</form>
</div>

<script src="js/app.js"></script>
</body>
</html>

js/app.js

const usernameEl = document.querySelector('#username');


const emailEl = document.querySelector('#email');
const passwordEl = document.querySelector('#password');
const confirmPasswordEl = document.querySelector('#confirm-password');

const form = document.querySelector('#signup');

const checkUsername = () => {


let valid = false;

const min = 3, max = 25;

const username = usernameEl.value.trim();

if (!isRequired(username)) {
showError(usernameEl, 'Username cannot be blank.');
} else if (!isBetween(username.length, min, max)) {
showError(usernameEl, `Username must be between ${min} and ${max}
characters.`)
} else {
showSuccess(usernameEl);
valid = true;
}
return valid;
};

const checkEmail = () => {


let valid = false;
const email = emailEl.value.trim();
if (!isRequired(email)) {
showError(emailEl, 'Email cannot be blank.');
} else if (!isEmailValid(email)) {
showError(emailEl, 'Email is not valid.')
} else {
showSuccess(emailEl);
valid = true;
}
return valid;
};

const checkPassword = () => {


let valid = false;

const password = passwordEl.value.trim();

if (!isRequired(password)) {
showError(passwordEl, 'Password cannot be blank.');
} else if (!isPasswordSecure(password)) {
showError(passwordEl, 'Password must has at least 8 characters that include
at least 1 lowercase character, 1 uppercase characters, 1 number, and 1 special
character in (!@#$%^&*)');
} else {
showSuccess(passwordEl);
valid = true;
}

return valid;
};

const checkConfirmPassword = () => {


let valid = false;
// check confirm password
const confirmPassword = confirmPasswordEl.value.trim();
const password = passwordEl.value.trim();

if (!isRequired(confirmPassword)) {
showError(confirmPasswordEl, 'Please enter the password again');
} else if (password !== confirmPassword) {
showError(confirmPasswordEl, 'The password does not match');
} else {
showSuccess(confirmPasswordEl);
valid = true;
}
return valid;
};

const isEmailValid = (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 isPasswordSecure = (password) => {


const re = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?
=.{8,})");
return re.test(password);
};

const isRequired = value => value === '' ? false : true;


const isBetween = (length, min, max) => length < min || length > max ? false :
true;

const showError = (input, message) => {


// get the form-field element
const formField = input.parentElement;
// add the error class
formField.classList.remove('success');
formField.classList.add('error');

// show the error message


const error = formField.querySelector('small');
error.textContent = message;
};

const showSuccess = (input) => {


// get the form-field element
const formField = input.parentElement;

// remove the error class


formField.classList.remove('error');
formField.classList.add('success');

// hide the error message


const error = formField.querySelector('small');
error.textContent = '';
}

form.addEventListener('submit', function (e) {


// prevent the form from submitting
e.preventDefault();

// validate fields
let isUsernameValid = checkUsername(),
isEmailValid = checkEmail(),
isPasswordValid = checkPassword(),
isConfirmPasswordValid = checkConfirmPassword();

let isFormValid = isUsernameValid &&


isEmailValid &&
isPasswordValid &&
isConfirmPasswordValid;

// submit to the server if the form is valid


if (isFormValid) {

}
});

const debounce = (fn, delay = 500) => {


let timeoutId;
return (...args) => {
// cancel the previous timer
if (timeoutId) {
clearTimeout(timeoutId);
}
// setup a new timer
timeoutId = setTimeout(() => {
fn.apply(null, args)
}, delay);
};
};

form.addEventListener('input', debounce(function (e) {


switch (e.target.id) {
case 'username':
checkUsername();
break;
case 'email':
checkEmail();
break;
case 'password':
checkPassword();
break;
case 'confirm-password':
checkConfirmPassword();
break;
}
}));

Ref:- https://www.javascripttutorial.net/javascript-dom/javascript-form-
validation/

You might also like