How to disable submit button until all input classes have class="valid" - javascript

I want to create a sign-up form. I have 6 inputs: First Name, Last Name, E-mail, Password, Password confirmation and a checkbox for user agreement. If inputs have class="valid", value is valid, otherwise invalid. I put all the classes a default class="invalid". I want to disable my submit button until all input fields have class="valid". According to my research, I saw that the button should be disabled first using the window.onload eventlistener, but I still couldn't figure out how to do it.
This is the basic form:
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name"/> </br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /></br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /></br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement</br>
<button type="submit" >Sign Up</button>
</form>
I am controlling checkbox validation with an eventlistener:
checkbox.addEventListener('click', (e) => {
if (e.target.checked) {
checkbox.classList.remove('invalid');
checkbox.classList.add('valid');
} else {
checkbox.classList.remove('valid');
checkbox.classList.add('invalid');
}
})
And for the rest, i am checking with regexs:
// Regex values
const regexs = {
fname: /^[a-zA-Z0-9]{3,24}$/,
lname: /^[a-zA-Z0-9]{3,24}$/,
email: /^([a-z\d\.-]+)#([a-z\d-]+)\.([a-z]{2,8})$/,
password: /^[\w#-]{8,20}$/
};
// Regex Validation
const validation = (input, regex) => {
if (regex.test(input.value)) {
input.classList.remove('invalid');
input.classList.add('valid');
} else {
input.classList.remove('valid');
input.classList.add('invalid');
}
}
inputs.forEach((input) => {
input.addEventListener('keyup', (e) => {
validation(e.target,regexs[e.target.attributes.name.value])
})
})

Something like this might come in handy.
var form = document.querySelector('.signup__form'), is_valid = false, fields, button;
form.addEventListener('change', function(){
fields = form.querySelectorAll('input');
button = form.querySelector('button');
for (var i = fields.length - 1; i >= 0; i--) {
if( fields[i].classList.contains('invalid') )
{
is_valid = false;
break;
}
is_valid = true;
}
is_valid ? button.removeAttribute('disabled'): button.setAttribute('disabled', 'disabled');
});
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name"/> <br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /><br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /><br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement<br>
<button type="submit" disabled>Sign Up</button>
</form>
Since you don't have all of your code, I'm adding a second example myself so that I can fully test the validation part.
But you just need to copy the above JavaScript code and set the button to disabled="disabled"in the first place.
var form = document.querySelector('.signup__form'),
is_valid = false,
fields, button;
form.addEventListener('change', function() {
fields = form.querySelectorAll('input');
button = form.querySelector('button');
for (var i = fields.length - 1; i >= 0; i--) {
if (fields[i].value.length) {
fields[i].classList.remove('invalid');
} else {
fields[i].classList.add('invalid');
}
if (fields[i].classList.contains('invalid')) {
is_valid = false;
break;
}
is_valid = true;
}
is_valid ? button.removeAttribute('disabled') : button.setAttribute('disabled', 'disabled');
});
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name" /> <br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /><br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /><br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement<br>
<button type="submit" disabled>Sign Up</button>
</form>
Note: This example does not follow because it does not validate the Checkbox.
#Enes, 1. kod parçacığındaki JavaScript kodunu kopyalarsan çalışacaktır. 2. Kodu test edebilmen için ekledim. Bir değer girilmişse onu doğru "valid" kabul eder.

I would try to the native use of HTML properties (pattern & required) and CSS instead of giving in to javascript. Just give it a go, and see how it feels like. Do note that I excluded a pattern on your email input.
The only thing I would use javascript for is to check if the password fields are the same, but I would do that by injecting the password of the first password input into the confirming password input's pattern attribute, replacing ^[\w#-]{8,20}$.
The pink background is just there to show-case the validation rules.
By the way, you got the wrong formatting on some of the HTML tags. You don't need an ending slash on input and you should type <br/>, not </br>.
input:invalid {
background-color: pink;
}
form:invalid button[type="submit"] {
opacity: 0.5;
}
<form class="signup__form" action="/">
<input type="text" required pattern="^[a-zA-Z0-9]{3,24}$" placeholder="Name"> <br/>
<input type="text" required pattern="^[a-zA-Z0-9]{3,24}$" placeholder="Last Name"><br/>
<input type="email" required placeholder="E-mail"><br/>
<input type="password" required pattern="^[\w#-]{8,20}$" placeholder="Password"><br/>
<input type="password" required pattern="^[\w#-]{8,20}$" placeholder="Password Confirm"><br/>
<input type="checkbox" required>User Agreement<br/>
<button type="submit" >Sign Up</button>
</form>

you can use required="required", then the submit won't be called before the field has value.

A solution which tests the number of invalid classes:
var checkbox = document.querySelector("input[type=checkbox]");
var inputs = document.querySelectorAll("input:not([type='checkbox'])");
var but = document.querySelector("button[type=submit]");
but.disabled= true;
checkbox.addEventListener('click', (e) => {
if (e.target.checked) {
checkbox.classList.remove('invalid');
checkbox.classList.add('valid');
} else {
checkbox.classList.remove('valid');
checkbox.classList.add('invalid');
}
but.disabled = !document.querySelectorAll("input.invalid").length == 0;
})
// Regex values
const regexs = {
fname: /^[a-zA-Z0-9]{3,24}$/,
lname: /^[a-zA-Z0-9]{3,24}$/,
email: /^([a-z\d\.-]+)#([a-z\d-]+)\.([a-z]{2,8})$/,
password: /^[\w#-]{8,20}$/
};
// Regex Validation
const validation = (input, regex) => {
if (regex.test(input.value)) {
input.classList.remove('invalid');
input.classList.add('valid');
} else {
input.classList.remove('valid');
input.classList.add('invalid');
}
}
inputs.forEach((input) => {
input.addEventListener('keyup', (e) => {
validation(e.target,regexs[e.target.attributes.name.value]);
but.disabled = !document.querySelectorAll("input.invalid").length == 0;
})
})
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name"/> </br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /></br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /></br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement</br>
<button type="submit" >Sign Up</button>
</form>

We will use couple of properties to validate the form which are required, pattern, disabled and also we will use CSS properties to control the form validation
input:invalid {
background-color: red;
}
form:invalid input[type="submit"] {
opacity: 0.5;
cursor: not-allowed;
}
<form class="login__form" action="/">
<input type="email" required placeholder="E-mail"><br/><br/>
<input type="password" required pattern="^[\w#-]{8,20}$" placeholder="Password"><br/><br/>
<input type="submit" >
</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>

How to make an error message for each empty form field

I am trying to display an error message for each empty field, my problem is that when I submit the form with an empty (one or two) field all the error messages appear. I want only one error message for each empty field to appear, not all of them.
HTML :
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our Terms and Services</p>
</form>
JavaScript:
const submitButton = document.querySelector('.form-button');
const errorField = document.querySelectorAll(".error-field");
const validate = (e) => {
e.preventDefault();
const firstName = document.getElementById("name");
const lastName = document.getElementById("last-name");
const email = document.getElementById("email");
const password = document.getElementById("password");
if(firstName.value < 1 ) {
errorField.forEach((f) => f.classList.toggle('error-active'));
errorField.forEach((c) => c.style.color = "red");
firstName.classList.toggle("invalid");
return false;
}
if (lastName.value < 1) {
errorField.forEach((f) => f.classList.toggle("error-active"));
errorField.forEach((c) => (c.style.color = "red"));
lastName.classList.toggle("invalid");
return false;
}
if (email.value < 1) {
errorField.forEach((f) => f.classList.toggle("error-active"));
errorField.forEach((c) => (c.style.color = "red"));
email.classList.toggle("invalid");
return false;
}
if (password.value < 1) {
errorField.forEach((f) => f.classList.toggle("error-active"));
errorField.forEach((c) => (c.style.color = "red"));
password.classList.toggle("invalid");
return false;
} else {
password.classList.remove("invalid");
errorField.classList.remove("error-active");
}
return true;
}
submitButton.addEventListener('click' , validate);
Hope this fixed your issue. Notice, password changed to passwordD and you were accessing all the error field without specifying which
const submitButton = document.querySelector('.form-button');
const errorField = document.querySelectorAll(".error-field");
const validate = (e) => {
e.preventDefault();
const firstName = document.getElementById("name");
const lastName = document.getElementById("last-name");
const email = document.getElementById("email");
const passwordD = document.getElementById("password");
if (firstName.value < 1) {
errorField[0].classList.toggle('error-active');
errorField[0].style.color = "red";
firstName.classList.toggle("invalid");
}
if (lastName.value < 1) {
errorField[1].classList.toggle("error-active");
errorField[1].style.color = "red";
lastName.classList.toggle("invalid");
}
if (email.value < 1) {
errorField[2].classList.toggle("error-active");
errorField[2].style.color = "red";
email.classList.toggle("invalid");
}
if (password.value < 1) {
errorField[3].classList.add("error-active");
errorField[3].style.color = "red";
passwordD.classList.toggle("invalid");
} else {
passwordD.classList.remove("invalid");
errorField.forEach((f) => {
f.classList.remove("error-active");
f.style.color = "black";
});
return true;
}
return false;
}
submitButton.addEventListener('click', validate);
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our Terms and Services</p>
</form>
I would suggest you to use a form validation JS plugin instead of reinveting the wheel, for example Form Validation Plugin
You can simplify your code a bit using a class for the inputs, and keeping track of an isValid boolean for the form. You were setting all error-fields with your code. Here, we are able to reference just the error-field that applies using closest() to find the encompassing label, then querySelector to find the error-field
el.closest('label').querySelector('.error-field');
const submitButton = document.querySelector('.form-button');
const validate = (e) => {
e.preventDefault();
let isValid = true
document.querySelectorAll('.validate').forEach(el => {
let error = el.closest('label').querySelector('.error-field').classList;
if (el.value.trim().length === 0) {
isValid = false;
error.add('error-active');
el.classList.add('invalid')
} else {
error.remove('error-active');
el.classList.remove('invalid')
}
})
return isValid;
}
submitButton.addEventListener('click', validate);
.error-field.error-active,
input.invalid{
color: #f00;
}
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" class='validate' name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" class='validate' name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" class='validate' name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" class='validate' name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our Terms and Services</p>
</form>
That's because inside each if statement you are looping through all the Error fields in the form and update it all. So what you can do is first add unique id for each dom entry in the HTML file such as err-password, error-name and so on then inside each if statement grab the relevant eror field that needs to show the error and update only that field.
Using nextElementSibling would simplify your code a lot here... Since the error message always is right after the input.
In the condition to show or not the error.. That is the value.length you have to check.
const submitButton = document.querySelector('.form-button');
const errorField = document.querySelectorAll(".error-field");
const validate = (e) => {
// Remove any already displayed error
errorField.forEach(function(error){
error.classList.remove("invalid");
})
// Loop through all inputs to check the value length
document.querySelectorAll("form input").forEach(function(input){
if(input.value.length < 1){
input.nextElementSibling.classList.toggle("invalid");
}
})
// Prevent submit only if there are errors shown
let errorCount = document.querySelectorAll(".error-field.invalid").length
if(errorCount){
e.preventDefault();
}
}
submitButton.addEventListener('click' , validate);
label{
display: block;
}
label p{
margin: 0;
}
.error-field{
display: none;
color: red;
}
.invalid{
display: inline-block;
}
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our Terms and Services</p>
</form>

How to count the number of selected elements?

I have a lot of elements which are used identical class-name. Now I need to calculate the number of selected items.
For e.g. something like this: (however this example doesn't work correctly)
$("#btn").click(function(){
if($(".necessarily").val() == ''){
$(".necessarily").css('border','1px solid red');
}
// also I want the number of input.necessarily which are empty
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<form name="frm" action="#">
<input name="first-name" class="necessarily" type="text" /><br><br>
<input name="last-name" class="necessarily" type="text" /><br><br>
<input name="email" class="necessarily" type="email" /><br><br>
<input name="password" class="necessarily" type="password" /><br><br>
<input name="address" class="anything" type="text" /><br><br>
<input name="btn" id="btn" type="submit" value="Register" />
</form>
Now I want the number of those inputs which are empty ..., How can I calculate that?
.val() method returns .value property of the first element in the collection. You can filter the empty inputs using the .filter() method and read the .length property of the filtered collection:
var $empty = $(".necessarily").filter(function() {
// you can use the `$.trim` method for trimming whitespaces
// return $.trim(this.value).length === 0;
return this.value.length === 0;
});
if ( $empty.length > 0 ) {
}
If you want to add a border to the empty fields you can declare a CSS class and use the .removeClass and .addClass methods:
CSS:
.red_border {
border: 1px solid red;
}
JavaScript:
var $empty = $(".necessarily").removeClass('red_border').filter(function() {
return this.value.length === 0;
}).addClass('red_border');
You'd do better looking at the HTML5 Contraint API rather than doing what you're currently doing, which is a more manual and time-consuming way.
Instead of giving each field a class 'necessarily' (sidenote: the word you need is 'necessary', not 'necessarily', or, better still, 'required') use the required attribute. So:
<input name="last-name" required type="text" />
Then in your jQuery you can target empty fields with:
$('input:invalid').css('border', 'solid 1px red');
If all you're doing is highlighting bad fields, you don't even need JavaScript for this. You can do the same thing via CSS:
input:invalid { border: solid 1px red; }
The only problem with that is the styling will be showed even before the user has filled out the form, which is almost never desirable. You could get round this by logging, via JS, when the form is submitted, and only then activating the styles:
JS:
$('form').on('submit', function() { $(this).addClass('show-errors'); });
CSS:
.show-errors input:invalid { border: solid 1px red; }
Try this code:
$("#btn").click(function(){
var selectedcount = $(".necessarily").length; //no. of elements with necessarily class name
var emptyInputCount=0;
$(".necessarily").each(function(){
if($(this).val() == ''){
emptyInputCount++;
}
});
Try with each loop on the target elements.
$(function() {
$("#btn").click(function() {
var i = 0;
$(".necessarily").each(function() {
if ($(this).val() == "") {
$(this).css('border', '1px solid red');
i++;
}
});
alert(i); //Number of input element with no value
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form name="frm" action="#">
<input name="first-name" class="necessarily" type="text" />
<br>
<br>
<input name="last-name" class="necessarily" type="text" />
<br>
<br>
<input name="email" class="necessarily" type="email" />
<br>
<br>
<input name="password" class="necessarily" type="password" />
<br>
<br>
<input name="address" class="anything" type="text" />
<br>
<br>
<input name="btn" id="btn" type="submit" value="Register" />
</form>
Hope this helps!
You can use filter() like following example bellow.
var empty_inputs = $('.necessarily').filter(function(){
return $(this).val()=='';
});
empty_inputs.length will return 3 in my example.
Hope this helps.
var empty_inputs = $('.necessarily').filter(function(){
return $(this).val()=='';
});
console.log(empty_inputs.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="first-name" class="necessarily" type="text" /><br><br>
<input name="last-name" class="necessarily" type="text" /><br><br>
<input name="email" class="necessarily" type="email" value="Register"/><br><br>
<input name="password" class="necessarily" type="password" /><br><br>
<input name="address" class="anything" type="text" value="Register"/><br><br>
<input name="btn" id="btn" type="submit" value="Register" />
Hope this helps.
You need to:
query all elements by className
filter the jQuery Collection in order to keep only the elements that have no value
doSomethingElse
so, this maybe could help you:
function CheckEmptyCtrl($) {
'use strict';
var self = this;
self.target = $('.necessarily');
self.empty = self.target.filter(function(index, item) {
return !($(item).val().trim());
});
$('#result').append(self.empty.length + ' elements have no values.');
console.log(self.empty.length, self.empty);
}
jQuery(document).ready(CheckEmptyCtrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div id="result"></div>
<form name="frm" action="#">
<input name="first-name" class="necessarily" type="text" value="notEmpty" /><br><br>
<input name="last-name" class="necessarily" type="text" /><br><br>
<input name="email" class="necessarily" type="email" /><br><br>
<input name="password" class="necessarily" type="password" /><br><br>
<input name="address" class="anything" type="text" /><br><br>
<input name="btn" id="btn" type="submit" value="Register" />
</form>
You need to loop over the all of the inputs and count how many are empty. In the same loop you can also count the number of .necessarily inputs which are empty.
This example will output the result to the .result span.
$("#btn").click(function() {
var inputs = $("form input");
var emptyNecessarilyCount = 0;
var totalEmpty = 0
inputs.each(function() {
if ($(this).val() == "") {
totalEmpty++;
if ($(this).hasClass('necessarily')) {
emptyNecessarilyCount++;
}
}
});
$('.result').append("Total: " + totalEmpty);
$('.result2').append("Necessarily: " + emptyNecessarilyCount);
});
span {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="frm" action="#">
<input name="first-name" class="necessarily" type="text" />
<br>
<input name="last-name" class="necessarily" type="text" />
<br>
<input name="email" class="necessarily" type="email" />
<br>
<input name="password" class="necessarily" type="password" />
<br>
<input name="address" class="anything" type="text" />
<br>
<input name="btn" id="btn" type="submit" value="Register" />
<span class="result"></span>
<span class="result2"></span>
</form>

javascript validation - Javascript not running

I'm trying to validate the inputs, so far I've created only two rules. One to test the phone number and another to test if the passwords entered at the same.
My problem is that for some reason my javascript isn't validating input. I have it referenced in <script>, I call it in the form onsubmit="return validate()". For some reason even with using an alert test to check that its run, that fails. So, I'm not really sure what's wrong, I could do with some extra eyes.
function validate() {
var errMsg = ""; /* stores the error message */
var result = true; /* assumes no errors */
var phonetest1 = true;
var phonetest2 = true;
/*get values from the form*/
var FirstName = document.getElementById("FirstName").value;
var Lastname = document.getElementById("Lastname").value;
var Email = document.getElementById("Email").value;
var Password = document.getElementById("Password").value;
var ConPassword = document.getElementById("ConPassword").value;
var Phone = document.getElementById("Phone").value;
var phonepatt1 = (/\(|0|\d|\)|\d|\d|\d|\d|\d|\d|\d|\d/);
var phonepatt2 = (/0|\d|\s|\d|\d|\d|\d|\d|\d|\d|\d/);
/* Rule one */
if (!phonepatt1.test(Phoneno)) {
phonetest1 = false;
}
if (!phonepatt2.test(Phoneno)) {
phonetest2 = false;
}
if (phonetest1 == false && phonetest2 == false) {
errMsg += "Your Phone number is incorrect .\n";
result = false;
}
alert("I'm running"); /* This isn't working */
/* Rule two */
if (ConPassword != Password) {
errMsg += "Please confirm your password .\n";
result = false;
}
if (errMsg != "") { //only display message box if there is something to show
alert(errMsg);
}
return result;
}
<H1>store Home Page</H1>
<p>Customer Registration: Register
<p>Customer Login: Login
<p>Manager Login Administrators
<form id="UserDetails" method="post" onsubmit="return validate()" action="index.htm">
<fieldset id="Details">
<legend>Your details:</legend>
<p>
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" id="FirstName" pattern="[a-zA-Z]+" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Lastname">Last Name</label>
<input type="text" name="LastName" id="Lastname" pattern="[a-zA-Z]+" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Email">Email</label>
<input type="text" name="Email" id="Email" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Password">Password</label>
<input type="text" name="Password" id="Password" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="ConPassword">Confirm Password</label>
<input type="text" name="ConPassword" id="ConPassword" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Phone">Phone Number</label>
<input type="text" name="Phone" id="Phone" maxlength="12" size="12" placeholder="(03)92251515" />
</p>
<input type="submit" value="Register Now!" />
<input type="reset" value="Reset" />
</fieldset>
</form>
You have wrog name in your JavaScript (should be Phone instead of Phoneno):
if (!phonepatt1.test(Phone)) {
phonetest1 = false;
}
if (!phonepatt2.test(Phone)) {
phonetest2 = false;
}

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