Validate login form through JavaScript (Suggestion) - javascript

I have used pure JavaScript to validate this login form consider the below example and also check out the live demo here https://codepen.io/uicreation/pen/xpdbKe
hope it will be help you to understand how JavaScript validation is works.
Live Demo
if(document.getElementsByClassName('firstForm')[0]){
document.getElementsByClassName('firstForm')[0].onsubmit = function(e){
e.preventDefault();
var field = this;
var email = field.querySelector('input[type=email]');
var pass = field.querySelector('input[type=password]');
var regex = /^(([^<>()[\]\\.,;:\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(!regex.test(email.value)){
console.log("enter a valid email address")
} else if(pass.value.length < 8){
console.log("password should be greater than 8 characters")
} else {
console.log("success!")
}
}
}
form {
margin: 30px 0 0 30px;
}
fieldset {
padding:5px;
}
label {
min-width:60px;
display: inline-block;
}
input[type=submit]{
margin-top:5px;
margin-left:5px;
}
<form class="firstForm" novalidate>
<fieldset>
<label>Email</label>
<input type="email" name="email" placeholder="Enter Email" />
</fieldset>
<fieldset>
<label>Password</label>
<input type="password" name="password" placeholder="Enter Password" />
</fieldset>
<input type="submit" value="Login" />
</form>

Related

How Do I Add An Error Message To An Incorrect Input With JS? [duplicate]

This question already has answers here:
how to check confirm password field in form without reloading page
(15 answers)
Closed 10 months ago.
I am trying to add some error messages to my inputs through JS, but I am not exactly sure how I should go about this, and everything I've tried does not function well.
I am trying to display an error, and prevent the form from submitting, if there is an error.
<form novalidate>
<label for="password">
<input type="password" name="password" id="password" placeholder="Password*" required minlength="8" />
<span id='pwmessage'></span>
</label>
<label for="confirmpassword">
<input type="password" name="confirm_password" id="confirm_password" placeholder=" Confirm password*" required minlength="8" />
<span id='cpwmessage'></span>
</label>
<button>Submit</button>
</form>
Just try this one! In here, the form won't be submitted if the password or confirm password is missing or the confirm password is not same as the first password.
function empty() {
if (document.getElementById("password").value == "") {
document.getElementById("pwmessage").innerHTML = "Enter at least one character to the password field";
return false;
}
if (document.getElementById("confirm_password").value != document.getElementById("password").value) {
document.getElementById("cpwmessage").innerHTML = "Please check your password and try again";
return false;
};
}
<form novalidate action='process.php' method='get'>
<label for="password">
<input type="password" name="password" id="password" placeholder="Password*" required minlength="8" /><br>
<span id='pwmessage'></span><br>
</label>
<label for="confirmpassword">
<input type="password" name="confirm_password" id="confirm_password" placeholder=" Confirm password*" required minlength="8" /><br>
<span id='cpwmessage'></span><br>
</label>
<input type="submit" value="submit" onClick="return empty()" />
</form>
Thanks and best regards!
There are plenty of form validation tutorials out there to give you further inspiration.
This version makes use of data attributes and is very scalable without the need for more javascript. More work will be needed for additional input types but should be enough to get you started.
//Set valudation on blur for each of the elements
document.querySelectorAll("[data-customvalidate] input").forEach(function(element) {
element.addEventListener("blur", function() {
validateField(this)
});
});
//Set form validation
document.querySelectorAll("[data-customvalidate").forEach(function(element) {
element.addEventListener("submit", function(event) {
let isNotValid = false;
//Go through each of the input element
this.querySelectorAll("input").forEach(function(input) {
//Validate the input and set the isNotValid flg
if (validateField(input) && !isNotValid) {
isNotValid = true;
}
});
//Stop the form submit if not valid
if (isNotValid) {
event.preventDefault();
}
});
});
//Main Validation Funtion
function validateField(field) {
let attributes = field.getAttributeNames();
let parent = field.parentNode
let errorField = parent.querySelector(".formError");
let isError = false;
//Required Vlidation
if (attributes.includes("required") && field.value === "") {
errorField.textContent = `The ${field.dataset.errorfieldname} field is required`;
isError = true;
//Min Length Validation
} else if (attributes.includes("minlength") && (field.value.length < field.getAttribute("minlength"))) {
errorField.textContent = `The mininmum length for ${field.dataset.errorfieldname} field is ${field.getAttribute("minlength")} characters`;
isError = true;
//Match Validation
} else if (attributes.includes("data-mustmatch")) {
let elementToMatch = document.getElementById(field.dataset.mustmatch);
if (elementToMatch.value !== field.value) {
errorField.textContent = `The ${elementToMatch.dataset.errorfieldname} and ${field.dataset.errorfieldname} do not match`;
isError = true;
}
}
parent.classList.toggle("error", isError);
return isError;
}
label {
display: block;
}
label:not(.error)>.formError {
display: none;
}
label>.formError {
color: red;
font-weight: bold;
padding-left: 1em;
}
<form novalidate data-customvalidate>
<label for="password">
<input type="password" name="password" id="password" placeholder="Password*" required minlength="8" data-errorfieldname="Password" />
<span class="formError"></span>
</label>
<label for="confirmpassword">
<input type="password" name="confirm_password" id="confirm_password" placeholder=" Confirm password*" required minlength="8" data-errorfieldname="Confirm Password" data-mustmatch="password" data-mustmatcherror= "Password and Confirm Password do not match" />
<span class="formError"></span>
</label>
<button>Submit</button>
</form>

eventListener works on click 1. But fails on click 2

So i am making a signup form with action="signup.inc.php" But im handling the validation in javascript.
If the fields are empty or the password don't match the input gets a red border and the placeholder is replaced.
This works perfectly on the first click. But as soon as i click again he just shoots to signup.inc.php.
I need those validations to be done before we go to the signup.inc.php file.
let signupForm = document.getElementById('signupForm');
let firstname = document.getElementById('firstname');
let lastname = document.getElementById('lastname');
let email = document.getElementById('email');
let username = document.getElementById('username');
let password = document.getElementById('password');
let passwordRepeat = document.getElementById('passwordRepeat');
let result = false;
function showError(input, message) {
let formControl = input.parentElement;
formControl.className = 'formControl error';
let error = input;
error.placeholder = message;
}
function showSucces(input) {
let formControl = input.parentElement;
formControl.className = 'formControl succes';
}
function requiredFields(inputArr) {
inputArr.forEach(function (input){
if (input.value.trim() === ''){
showError(input, 'this field is required');
} else {
showSucces(input);
result = true;
}
});
}
function matchPasswords(input1, input2) {
if (input1.value !== input2.value) {
showError(input2, "These passwords don't match");
} else {
result = true;
}
}
/* Eventlistener */
signupForm.addEventListener('submit', function(e){
if (result !== true) {
requiredFields ([firstname, lastname, email, username, password, passwordRepeat]);
matchPasswords (password, passwordRepeat);
e.preventDefault();
} else {
result = true;
}
});
.signupFormWrap {
margin-bottom: 15px;
}
.signupFormWrap,
.formControl {
width: 400px;
display: flex;
flex-direction: column;
}
.formControl label {
font-size: 1.2rem;
}
.formControl>input[type=text],
input[type=email],
input[type=password] {
padding-left: 10px;
font-size: 1rem;
line-height: 1.8;
}
.button {
margin-top: 15px;
margin-bottom: 15px;
}
.formControl.error>input {
border: 1px solid red;
}
.formControl.succes>input {
border: 1px solid green;
}
<form name="signupForm" id="signupForm" action="assets/php/signup.inc.php" method="POST">
<div class="signupFormWrap">
<div class="formControl">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="firstname" placeholder="Fill in your firstname here..">
</div>
<div class="formControl">
<label for="lastname">lastname</label>
<input type="text" name="lastname" id="lastname" placeholder="Fill in your lastname here..">
</div>
<div class="formControl">
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="Fill in your email here..">
</div>
<div class="formControl">
<label for="username">Username</label>
<input type="text" name="username" id="username" placeholder="Fill in your username here..">
</div>
<div class="formControl">
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="fill in your password here..">
</div>
<div class="formControl">
<label for="passwordRepeat">Verify your password</label>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="Verify your password">
</div>
<button type="submit" name="submit" class="button">Sign up</button>
</div>
</form>
Your problem is that if any of the inputs are valid, result is set to true and so on the next submit the inputs are not checked and the form submits. You can work around that by always testing all the inputs, returning the error status from each input checking function and checking that they all return true:
let signupForm = document.getElementById('signupForm');
let firstname = document.getElementById('firstname');
let lastname = document.getElementById('lastname');
let email = document.getElementById('email');
let username = document.getElementById('username');
let password = document.getElementById('password');
let passwordRepeat = document.getElementById('passwordRepeat');
function showError(input, message) {
let formControl = input.parentElement;
formControl.className = 'formControl error';
let error = input;
error.placeholder = message;
}
function showSucces(input) {
let formControl = input.parentElement;
formControl.className = 'formControl succes';
}
function requiredFields(inputArr) {
result = true;
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, 'this field is required');
result = false;
} else {
showSucces(input);
}
});
return result;
}
function matchPasswords(input1, input2) {
result = true;
if (input1.value !== input2.value) {
showError(input2, "These passwords don't match");
result = false;
}
return result;
}
/* Eventlistener */
signupForm.addEventListener('submit', function(e) {
let result = true;
result = result && requiredFields([firstname, lastname, email, username, password, passwordRepeat]);
result = result && matchPasswords(password, passwordRepeat);
if (!result) {
e.preventDefault();
}
});
.signupFormWrap {
margin-bottom: 15px;
}
.signupFormWrap,
.formControl {
width: 400px;
display: flex;
flex-direction: column;
}
.formControl label {
font-size: 1.2rem;
}
.formControl>input[type=text],
input[type=email],
input[type=password] {
padding-left: 10px;
font-size: 1rem;
line-height: 1.8;
}
.button {
margin-top: 15px;
margin-bottom: 15px;
}
.formControl.error>input {
border: 1px solid red;
}
.formControl.succes>input {
border: 1px solid green;
}
<form name="signupForm" id="signupForm" action="assets/php/signup.inc.php" method="POST">
<div class="signupFormWrap">
<div class="formControl">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="firstname" placeholder="Fill in your firstname here..">
</div>
<div class="formControl">
<label for="lastname">lastname</label>
<input type="text" name="lastname" id="lastname" placeholder="Fill in your lastname here..">
</div>
<div class="formControl">
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="Fill in your email here..">
</div>
<div class="formControl">
<label for="username">Username</label>
<input type="text" name="username" id="username" placeholder="Fill in your username here..">
</div>
<div class="formControl">
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="fill in your password here..">
</div>
<div class="formControl">
<label for="passwordRepeat">Verify your password</label>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="Verify your password">
</div>
<button type="submit" name="submit" class="button">Sign up</button>
</div>
</form>
change all validation functions like
function matchPasswords(input1, input2) {
if (input1.value !== input2.value) {
showError(input2, "These passwords don't match");
return false;
}
return true;
}
signupForm.addEventListener('submit', function(e){
if(!requiredFields ([firstname, lastname, email, username, password, passwordRepeat]) &&
!matchPasswords (password, passwordRepeat)){
e.preventDefault();
}
});

Javascript cannot submit form with empty field validation

I have a small issue with my code not submitting my form. Once I fill out the form and press the submit button, nothing simply happens, it seems like the form is not being submitted. In practice, this code should check whether there are any empty fields and if so, it prompts a message instructing to fill out the fields. If every field filled out, submit the form.
function storeUser() {
var userObject = {};
userObject.username = document.getElementById("username").value;
userObject.email = document.getElementById("inputEmail").value;
userObject.password = document.getElementById("inputPassword").value;
userObject.passwordConfirm = document.getElementById("inputPasswordConfirm").value;
userObject.mobileNumber = document.getElementById("inputNumber").value;
userObject.score = 0;
if (userObject.password !== userObject.passwordConfirm) {
document.getElementById("Warning").innerHTML = "Your password doesn't match.";
return false;
}
if (userObject.username === "") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
}
if (userObject.email === " " ) {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
}
if (userObject.password === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
}
if (userObject.passwordConfirm === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
}
if (userObject.mobileNumber === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
return false;
}
else {
return true;
}
localStorage[userObject.email] = JSON.stringify(userObject);
document.getElementById("Result").innerHTML = "Success! You have registered your account.";
As you most probably noticed, I'm a complete novice to this. Aynone could lead me the right way?
EDIT:
<form class="form-container" name="registerForm" onsubmit="return false">
<p><b>Please fill out all fields to register your account</b></p>
<div class="form-group">
<input type="text" class="form-control" id="username" aria-describedby="username" placeholder="Username" minlength=3 required>
</div>
<div class="form-group">
<input type="email" class="form-control" id="inputEmail" aria-describedby="emailHelp" placeholder="Enter email" required>
</div>
<div class="form-group">
<input type="password" class="form-control" id="inputPassword" placeholder="Password" required>
</div>
<div class="form-group">
<input type="password" class="form-control" id="inputPasswordConfirm" placeholder="Confirm password" required>
</div>
<div class="form-group">
<input type="tel" class="form-control" id="inputNumber" placeholder="Mobile number" pattern="^\s*\(?(020[7,8]{1}\)?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3}\)?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})\s*$" required>
</div>
<button type="submit" onclick="storeUser()" class="btn btn-primary regstrbtn">Register</button>
<p id="Result"></p>
<p id="Warning" style="color: red;"></p>
</form>
Looking at your code I found a number of problems:
Invalid telephone number regexp: you are using the following regexp to validate the telephone number field, but it has a missing character:
^\s*\(?(020[7,8]{1}\)?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3}\)?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})\s*$
// missing ] after 0-9 ^^
(I am going to ignore the fact that the regular expression has placeholder 'Mobile number' yet only accepts landline phone numbers for inner and outer London in the UK.)
You are showing validation error messages if the email, password, confirm-password and telephone number fields contain a single space:
if (userObject.email === " " ) {
You probably want to be comparing the values against an empty string instead:
if (userObject.email === "" ) {
The end of your storeUser() function is as follows:
if (userObject.mobileNumber === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
return false;
}
else {
return true;
}
localStorage[userObject.email] = JSON.stringify(userObject);
document.getElementById("Result").innerHTML = "Success! You have registered your account.";
When do we reach the last two lines, the one that writes to local storage and the one that shows the success message?
If the telephone number field contains a single space, then a warning message appears and the function returns false.
If the telephone number field contains anything other than a single space, the function returns true.
The last two lines are unreachable. They are never executed because the function returns before it gets to them.
What you probably want to do is to get rid of the else clause and add return true; at the bottom, i.e.:
if (userObject.mobileNumber === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
return false;
}
localStorage[userObject.email] = JSON.stringify(userObject);
document.getElementById("Result").innerHTML = "Success! You have registered your account.";
return true;
Inconsistent use of return false;. If the passwords don't match, or the telephone number field isn't filled out, the function returns false. There is no corresponding return false; line for the username, email, password and confirm-password fields. Add this line for each of these fields.
You aren't clearing the warning message if the form is successfully completed. Add the line
document.getElementById("Warning").innerHTML = "";
to the end of your function.
Incidentally you have various pairs of lines
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
but the first line in each pair is unnecessary because the empty-string value you assign to the inner HTML of the warning element is immediately replaced by the warning message assigned in the second line. You can delete the first line of each such pair.
You can simply manage this using HTML5 form field validators, please find below code snippet:
body {
font-family: Helvetica, Arial;
font-size:12px;
}
h1 {
font-size:200%;
}
legend {
padding:0 5px;
text-align:right;
}
fieldset > div {
margin:10px 0;
}
fieldset > legend + div {
margin-top:0;
}
fieldset > div:last-child {
margin-bottom:0;
}
label {
display:inline-block;
width:100px;
}
input {
width:200px;
}
input[type="number"] {
width:30px;
}
div > input[type="submit"] {
background: #ccc;
border:1px solid #999;
width:auto;
}
input:required {
background:hsl(180, 50%, 90%);
border:1px solid #999;
}
input:optional {
background:hsl(300, 50%, 90%);
border:1px dotted hsl(180, 50%, 90%);
}
input:valid,
input:in-range {
background:hsl(120, 50%, 90%);
border-color:hsl(120, 50%, 50%);
}
input:invalid,
input:out-of-range {
border-color:hsl(0, 50%, 50%);
background:hsl(0, 50%, 90%);
}
.help {
display:none;
font-size:90%;
}
input:focus + .help {
display:inline-block;
}
div.submit {
margin-left:100px;
}
<form action="" method="post">
<fieldset>
<legend>Booking Details</legend>
<div>
<label for="name">Name:</label>
<input id="name" name="name" value="" required pattern="[A-Za-z-0-9]+\s[A-Za-z-'0-9]+" title="firstname lastname" aria-required="true" aria-describedby="name-format">
<span id="name-format" class="help">Format: firstname lastname</span>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="" required aria-required="true">
</div>
<div>
<label for="website">Website:</label>
<input type="url" id="website" name="website" value="">
</div>
<div>
<label for="numTickets"><abbr title="Number">No.</abbr> of Tickets:</label>
<input type="number" id="numTickets" name="numTickets" value="" required aria-required="true" min="1" max="4">
</div>
<div class="submit">
<input type="submit" value="Submit">
</div>
</fieldset>
</form>

It is about validation of form

**Below is the code for basic user registration form but it is not validating the form... Please can anyone tell me where is the problem. Except validation remaining code is working. Please tell me what to do for it*
function validateForm()
{
var fName = document.forms["myForm"]["fName"].value;
var lName = document.forms["myForm"]["lName"].value;
var email = document.forms["myForm"]["email"].value;
var username = document.forms["myForm"]["username"].value;
var pwd = document.forms["myForm"]["pwd"].value;
var password = document.forms["myForm"]["password"].value;
var mobile = document.forms["myForm"]["mobile"].value;
var emailreg = /^[\w._-]+[+]?[\w._-]+#[\w.-]+\.[a-zA-Z]{2,6}$/;
var usernamereg = /^[a-zA-Z0-9]+([-_\.][a-zA-Z0-9]+)*[a-zA-Z0-9])$/;
var pwdreg = /^(?=.*\d)(?=.*[a-zA-Z0-9])(?=.*[!#$%&? "])$/;
if(fName!="" && lName!="" && email!="" && username!="" && pwd!="" &&
password!="" && mobile!="")
{
if(email.match(emailreg))
{
if(username.match(usernamereg))
{
if(pwd.match(pwdreg))
{
if(pwd.match(password))
{
alert("You are Successfully Registered");
return true;
}
else
{
alert("Both Password do not match");
return false;
}
}
else
{
alert("Enter valid Password");
return false;
}
}
else
{
alert("Enter valid username");
return false;
}
}
else
{
alert("Enter a valid Email");
return false;
}
}
else
{
alert("All Fields are required");
return false;
}
}
#outer
{
height:650px;
width:1350px;
border:1px solid;
background-image:url("image.jpeg");
color:white;
font-size:22px;
}
#form
{
height:500px;
width:220px;
opacity:0.8;
margin-left:850px;
margin-top:70px;
background-color:black;
}
.a
{
height:40px;
width:180px;
border-radius:5px;
margin-top:20px;
margin-left:20px;
}
.b
{
height:40px;
width:180px;
border-radius:5px;
margin-top:20px;
margin-left:20px;
background-color:aqua;
}
<html>
<head>
</head>
<body>
<div id="outer">
<center><h2> Registration Form</h2></center>
<div id="form">
<form name="myForm" action="register.php" onsubmit="return
validateForm()" method="POST">
<input class="a" type="text" name="fName" placeholder="Enter your
first name"/>
<input class="a" type="text" name="lName" placeholder="Enter your
last name"/>
<input class="a" type="email" name="email" placeholder="Enter your
email"/>
<input class="a" type="text" name="username" placeholder="Select
your username"/>
<input class="a" type="password" name="pwd" placeholder="Enter
your password"/>
<input class="a" type="password" name="password"
placeholder="Confirm your password"/>
<input class="a" type="number" name="mobile" placeholder="Enter
your mobile no"/>
<input class="b" type="Submit" value="REGISTER"/ name="register">
</form>
</div>
</div >
</body>
</html>
Here you made several mistake in your code.
Make sure onsubmit="return validateForm()" have no any blank space before return
There is a error in your regular expression
var usernamereg = /^([a-zA-Z0-9]+([-_\.][a-zA-Z0-9]+)*[a-zA-Z0-9])$/; You made mistake in this. you forget to add ( at the starting of expression after /^
Below is the working snippet with validation.
Check it hope it will helps you
function validateForm()
{
var fName = document.forms["myForm"]["fName"].value;
var lName = document.forms["myForm"]["lName"].value;
var email = document.forms["myForm"]["email"].value;
var username = document.forms["myForm"]["username"].value;
var pwd = document.forms["myForm"]["pwd"].value;
var password = document.forms["myForm"]["password"].value;
var mobile = document.forms["myForm"]["mobile"].value;
var emailreg = /^[\w._-]+[+]?[\w._-]+#[\w.-]+\.[a-zA-Z]{2,6}$/;
var usernamereg = /^([a-zA-Z0-9]+([-_\.][a-zA-Z0-9]+)*[a-zA-Z0-9])$/;
var pwdreg = /^(?=.*\d)(?=.*[a-zA-Z0-9])(?=.*[!#$%&? "])$/;
if(fName!="" && lName!="" && email!="" && username!="" && pwd!="" &&
password!="" && mobile!="")
{
if(email.match(emailreg))
{
if(username.match(usernamereg))
{
if(pwd.match(pwdreg))
{
if(pwd.match(password))
{
alert("You are Successfully Registered");
return true;
}
else
{
alert("Both Password do not match");
return false;
}
}
else
{
alert("Enter valid Password");
return false;
}
}
else
{
alert("Enter valid username");
return false;
}
}
else
{
alert("Enter a valid Email");
return false;
}
}
else
{
alert("All Fields are required");
return false;
}
}
#outer
{
height:650px;
width:1350px;
border:1px solid;
background-image:url("image.jpeg");
color:white;
font-size:22px;
}
#form
{
height:500px;
width:220px;
opacity:0.8;
margin-left:850px;
margin-top:70px;
background-color:black;
}
.a
{
height:40px;
width:180px;
border-radius:5px;
margin-top:20px;
margin-left:20px;
}
.b
{
height:40px;
width:180px;
border-radius:5px;
margin-top:20px;
margin-left:20px;
background-color:aqua;
}
<body>
<div id="outer">
<center><h2> Registration Form</h2></center>
<div id="form">
<form name="myForm" action="register.php" onsubmit="return validateForm()" method="POST">
<input class="a" type="text" name="fName" placeholder="Enter your
first name"/>
<input class="a" type="text" name="lName" placeholder="Enter your
last name"/>
<input class="a" type="email" name="email" placeholder="Enter your
email"/>
<input class="a" type="text" name="username" placeholder="Select
your username"/>
<input class="a" type="password" name="pwd" placeholder="Enter
your password"/>
<input class="a" type="password" name="password"
placeholder="Confirm your password"/>
<input class="a" type="number" name="mobile" placeholder="Enter
your mobile no"/>
<input class="b" type="Submit" value="REGISTER"/ name="register">
</form>
</div>
</div >
</body>

how to check confirm password field in form without reloading page

I have a project in which I have to add a registration form and I want to to validate that the password and confirm fields are equal without clicking the register button.
If password and confirm password field will not match, then I also want to put an error message at side of confirm password field and disable registration button.
following is my html code..
<form id="form" name="form" method="post" action="registration.php">
<label >username :
<input name="username" id="username" type="text" /></label> <br>
<label >password :
<input name="password" id="password" type="password" /></label>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" />
</label>
<label>
<input type="submit" name="submit" value="registration" />
</label>
Is there any way to do this?
We will be looking at two approaches to achieve this. With and without using jQuery.
1. Using jQuery
You need to add a keyup function to both of your password and confirm password fields. The reason being that the text equality should be checked even if the password field changes. Thanks #kdjernigan for pointing that out
In this way, when you type in the field you will know if the password is same or not:
$('#password, #confirm_password').on('keyup', function () {
if ($('#password').val() == $('#confirm_password').val()) {
$('#message').html('Matching').css('color', 'green');
} else
$('#message').html('Not Matching').css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>password :
<input name="password" id="password" type="password" />
</label>
<br>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" />
<span id='message'></span>
</label>
and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/325/
2. Without using jQuery
We will use the onkeyup event of javascript on both the fields to achieve the same effect.
var check = function() {
if (document.getElementById('password').value ==
document.getElementById('confirm_password').value) {
document.getElementById('message').style.color = 'green';
document.getElementById('message').innerHTML = 'matching';
} else {
document.getElementById('message').style.color = 'red';
document.getElementById('message').innerHTML = 'not matching';
}
}
<label>password :
<input name="password" id="password" type="password" onkeyup='check();' />
</label>
<br>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" onkeyup='check();' />
<span id='message'></span>
</label>
and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/324/
Using Native setCustomValidity
Compare the password/confirm-password input values on their change event and setCustomValidity accordingly:
function onChange() {
const password = document.querySelector('input[name=password]');
const confirm = document.querySelector('input[name=confirm]');
if (confirm.value === password.value) {
confirm.setCustomValidity('');
} else {
confirm.setCustomValidity('Passwords do not match');
}
}
<form>
<label>Password: <input name="password" type="password" onChange="onChange()" /> </label><br />
<label>Confirm : <input name="confirm" type="password" onChange="onChange()" /> </label><br />
<input type="submit" />
</form>
If you don't want use jQuery:
function check_pass() {
if (document.getElementById('password').value ==
document.getElementById('confirm_password').value) {
document.getElementById('submit').disabled = false;
} else {
document.getElementById('submit').disabled = true;
}
}
<input type="password" name="password" id="password" onchange='check_pass();'/>
<input type="password" name="confirm_password" id="confirm_password" onchange='check_pass();'/>
<input type="submit" name="submit" value="registration" id="submit" disabled/>
Solution Using jQuery
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<style>
#form label{float:left; width:140px;}
#error_msg{color:red; font-weight:bold;}
</style>
<script>
$(document).ready(function(){
var $submitBtn = $("#form input[type='submit']");
var $passwordBox = $("#password");
var $confirmBox = $("#confirm_password");
var $errorMsg = $('<span id="error_msg">Passwords do not match.</span>');
// This is incase the user hits refresh - some browsers will maintain the disabled state of the button.
$submitBtn.removeAttr("disabled");
function checkMatchingPasswords(){
if($confirmBox.val() != "" && $passwordBox.val != ""){
if( $confirmBox.val() != $passwordBox.val() ){
$submitBtn.attr("disabled", "disabled");
$errorMsg.insertAfter($confirmBox);
}
}
}
function resetPasswordError(){
$submitBtn.removeAttr("disabled");
var $errorCont = $("#error_msg");
if($errorCont.length > 0){
$errorCont.remove();
}
}
$("#confirm_password, #password")
.on("keydown", function(e){
/* only check when the tab or enter keys are pressed
* to prevent the method from being called needlessly */
if(e.keyCode == 13 || e.keyCode == 9) {
checkMatchingPasswords();
}
})
.on("blur", function(){
// also check when the element looses focus (clicks somewhere else)
checkMatchingPasswords();
})
.on("focus", function(){
// reset the error message when they go to make a change
resetPasswordError();
})
});
</script>
And update your form accordingly:
<form id="form" name="form" method="post" action="registration.php">
<label for="username">Username : </label>
<input name="username" id="username" type="text" /></label><br/>
<label for="password">Password :</label>
<input name="password" id="password" type="password" /><br/>
<label for="confirm_password">Confirm Password:</label>
<input type="password" name="confirm_password" id="confirm_password" /><br/>
<input type="submit" name="submit" value="registration" />
</form>
This will do precisely what you asked for:
validate that the password and confirm fields are equal without clicking the register button
If password and confirm password field will not match it will place an error message at the side of confirm password field and disable registration button
It is advisable not to use a keyup event listener for every keypress because really you only need to evaluate it when the user is done entering information. If someone types quickly on a slow machine, they may perceive lag as each keystroke will kick off the function.
Also, in your form you are using labels wrong. The label element has a "for" attribute which should correspond with the id of the form element. This is so that when visually impaired people use a screen reader to call out the form field, it will know text belongs to which field.
function check() {
if(document.getElementById('password').value ===
document.getElementById('confirm_password').value) {
document.getElementById('message').innerHTML = "match";
} else {
document.getElementById('message').innerHTML = "no match";
}
}
<label>password :
<input name="password" id="password" type="password" />
</label>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" onchange="check()"/>
<span id='message'></span>
HTML CODE
<input type="text" onkeypress="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>
<input type="text" onkeypress="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>
JS CODE
function checkPass(){
var pass = document.getElementById("password").value;
var rpass = document.getElementById("rpassword").value;
if(pass != rpass){
document.getElementById("submit").disabled = true;
$('.missmatch').html("Entered Password is not matching!! Try Again");
}else{
$('.missmatch').html("");
document.getElementById("submit").disabled = false;
}
}
try using jquery like this
$('input[type=submit]').click(function(e){
if($("#password").val() == "")
{
alert("please enter password");
return false;
}
});
also add this line in head of html
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
$('input[type=submit]').on('click', validate);
function validate() {
var password1 = $("#password1").val();
var password2 = $("#password2").val();
if(password1 == password2) {
$("#validate-status").text("valid");
}
else {
$("#validate-status").text("invalid");
}
}
Logic is to check on keyup if the value in both fields match or not.
Working fiddle: http://jsfiddle.net/dbwMY/
More details here: Checking password match while typing
<form id="form" name="form" method="post" action="registration.php" onsubmit="return check()">
....
</form>
<script>
$("#form").submit(function(){
if($("#password").val()!=$("#confirm_password").val())
{
alert("password should be same");
return false;
}
})
</script>
hope it may help you
Try this one ;
CSS
#indicator{
width:20px;
height:20px;
display:block;
border-radius:10px;
}
.green{
background-color:green;
display:block;
}
.red{
background-color:red;
display:block;
}
HTML
<form id="form" name="form" method="post" action="registration.php">
<label >username :
<input name="username" id="username" type="text" /></label> <br>
<label >password :
<input name="password" id="password" type="password" id="password" /></label> <br>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" /><span id="indicator"></span> <br>
</label>
<label>
<input type="submit" name="submit" id="regbtn" value="registration" />
</label>
</form>
JQuery
$('#confirm_password').keyup(function(){
var pass = $('#password').val();
var cpass = $('#confirm_password').val();
if(pass!=cpass){
$('#indicator').attr({class:'red'});
$('#regbtn').attr({disabled:true});
}
else{
$('#indicator').attr({class:'green'});
$('#regbtn').attr({disabled:false});
}
});
WITHOUT clicking the button you will have to listen to the change event of the input fields
var confirmField = document.getElementById("confirm_password");
var passwordField = document.getElementById("password");
function checkPasswordMatch(){
var status = document.getElementById("password_status");
var submit = document.getElementById("submit");
status.innerHTML = "";
submit.removeAttribute("disabled");
if(confirmField.value === "")
return;
if(passwordField.value === confirmField.value)
return;
status.innerHTML = "Passwords don't match";
submit.setAttribute("disabled", "disabled");
}
passWordField.addEventListener("change", function(event){
checkPasswordMatch();
});
confirmField.addEventListener("change", function(event){
checkPasswordMatch();
});
then add the status element to your html:
<p id="password_status"></p>
and set the submit button id to submit
... id="submit" />
hope this helps you
$box = $('input[name=showPassword]');
$box.focus(function(){
if ($(this).is(':checked')) {
$('input[name=pswd]').attr('type', 'password');
} else {
$('input[name=pswd]').attr('type', 'text');
}
})
You can check confirm password by only simple javascript
html
<input type="password" name="password" required>
<input type="password" name="confirmpassword" onkeypress="register()" required>
<div id="checkconfirm"></div>
and in javascript
function register() {
var password= document.getElementById('password').value ;
var confirm= document.getElementById('confirmpassword').value;
if (confirm!=password){
var field = document.getElementById("checkconfirm")
field.innerHTML = "not match";
}
}
Also you can use onkeyup instead of onkeypress.
The code proposed by #Chandrahasa Rai
works almost perfectly good, with one exception!
When triggering function checkPass(), i changed onkeypress to onkeyup so the last key pressed can be processed too. Otherwise when You type a password, for example: "1234", when You type the last key "4", the script triggers checkPass() before processing "4", so it actually checks "123" instead of "1234". You have to give it a chance by letting key go up :)
Now everything should be working fine!
#Chandrahasa Rai,
HTML code:
<input type="text" onkeypress="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>
<input type="text" onkeypress="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>
#my modification:
<input type="text" onkeyup="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>
<input type="text" onkeyup="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>
I think this example is good to check https://codepen.io/diegoleme/pen/surIK
I can quote code here
<form class="pure-form">
<fieldset>
<legend>Confirm password with HTML5</legend>
<input type="password" placeholder="Password" id="password" required>
<input type="password" placeholder="Confirm Password" id="confirm_password" required>
<button type="submit" class="pure-button pure-button-primary">Confirm</button>
</fieldset>
</form>
and
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;

Categories

Resources