How can I implement this regex for number validation in a form? - javascript

If I enter the exact number of 300000, the form is submitted. Any other value below or above 300000 causes the error message to display. The error message should only display when the value is less than 300000. What's the error in my code?
document.addEventListener("DOMContentLoaded", function() {
document.querySelector('#sbutton').addEventListener('click', function(event) {
event.preventDefault();
let inputV = document.querySelector('#budget').value.trim();
let budgetRegex = /^3[0-9]{5,}/;
const errorMessage = document.querySelector('#errormsg');
let form = document.querySelector("form");
if (inputV == "" || !budgetRegex.test(inputV)) {
errorMessage.innerHTML = "Value should be at least 300,000.";
errorMessage.style.display = 'block';
} else {
errorMessage.innerHTML = "";
errorMessage.style.display = 'none';
form.submit();
}
});
});
<form action="https://dragonmm.xyz" method="post">
<div class="contact-box">
<div class="left1"></div>
<div class="right1">
<h2>Start</h2>
<label for="name"></label>
<input id="name" type="text" class="field" placeholder="Name" required>
<label for="email"></label>
<input id="email" type="text" class="field" placeholder="Email" required>
<label for="phone"></label>
<input id="phone" type="text" class="field" placeholder="Phone" required>
<label for="budget"></label>
<input id="budget" type="text" name="budget" class="field budgetInput" placeholder="Budget" required>
<div id="errormsg"></div>
</div>
</div>
<button type="submit" value="Send" class="btn1" id="sbutton">Send</button>
</form>

Use a numeric input field (type="number"). Use the min attribute of the field to limit the input (although a user can still input her own text). Next, convert values to Number, so you can do calculations.
Here's a minimal example, using event delegation.
Finally: you should always check values server side too.
document.addEventListener(`input`, handle);
function handle(evt) {
if (evt.target.id === "budget") {
if (+evt.target.value < +evt.target.min) {
// ^convert to Number
return document.querySelector(`#budgetError`)
.classList.remove(`hidden`);
}
return document.querySelector(`#budgetError`)
.classList.add(`hidden`);
}
}
#budgetError {
color: red;
}
.hidden {
display: none;
}
<input id="budget" type="number" min="300000"> budget
<div id="budgetError" class="hidden">
Not enough! We need at least 300,000</div>

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>

html form validation using javascript

i am trying to validate my html form using javascript. the validation works but it still submits.
ie. when clicking submit a text will appear saying "first name is required" but then still submits.
here is the javascript code:
function validateForm(form) {
formValid = true;
for(i = 0; i < form.length; i++) {
if(!requiredInput(form[i]))
formValid = false;
}
return formValid;
}
function requiredInput(element) {
if(!element.value.length) {
document.getElementById(element.id + 'Error').style.display = "inline-block";
return false;
} else {
document.getElementById(element.id + 'Error').style.display = "none";
return true;
}
return;
}
and here is the html code for the form:
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get" onsubmit="return validateForm(this);">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit" >
</div>
</form>
im not sure why it still submits.
EDIT: i need to debug this code and not change all of it
EDIT: i can not change the html code for this, i am to debug the javascript only
I think you need validate if its type submit :
function validateForm(form) {
formValid = true;
for(i = 0; i < form.length; i++) {
if(form[i].type != "submit"){
if(!requiredInput(form[i])){
formValid = false;
}
}
}
return formValid;
}
Your validation has the correct structure, however, if there is any JavaScript error, the "return false" will not cancel the form submission.
Go to your developer console and manually invoke the validateForm function. You can give the form an ID:
<form id="myform"...
Then, you can reference this in the console:
validateForm(document.getElementById('form'));
You will see a JavaScript error. Fix the error and your form will be intercepted.
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get"
onsubmit="return validateForm(event)">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit">
</div>
<script type="text/javascript">
function validateForm(e) {
form = e.target;
formValid = true;
for (i = 0; i < form.length; i++) {
if (!requiredInput(form[i]))
formValid = false;
}
return formValid;
}
function requiredInput(element) {
if (element.type == 'submit') {
return true;
}
if (element.value.length == 0) {
document.getElementById(element.id + 'Error').style.display = "inline-block";
return false;
} else {
document.getElementById(element.id + 'Error').style.display = "none";
return true;
}
}
this should work
Actually You can do it simple way, see below,
Modify your HTML
I remove onsubmit attribute and add form to ID
<form id="dsds" action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit" >
</div>
Remove your JS function and do like this,
$("#dsds").submit(function(e){
//call your functions here
return false; // return true if you want to submit the form
});
See the example,
JSFille
Use preventDefault() to disable the submit.
function validateForm(event, form) {
formValid = true;
for (i = 0; i < form.length; i++) {
if (!requiredInput(form[i])) {
formValid = false;
break;
}
}
if (!formValid) {
event.preventDefault();
}
return formValid;
}
And pass the event object in the onsubmit function like below.
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get" onsubmit="validateForm(event, this);">
function validateForm(form) {
formValid = true;
try {
for (i = 0; i < form.length; i++) {
if (!requiredInput(form[i]))
formValid = false;
}
} catch (error) {
console.error("validateForm=>", error)
}
return formValid;
}
function requiredInput(element) {
try {
const elementInputError = document.getElementById(element.id + 'Error');
if (!element.value.length) {
elementInputError && setDisplayError(elementInputError,"inline-block");
return false;
} else {
elementInputError && setDisplayError(elementInputError,"none");
return true;
}
} catch (error) {
console.error("requiredInput=>", error)
return false;
}
}
function setDisplayError(element,value) {
try {
element.style.display =value;
} catch (error) {
console.error("setDisplayError=>", error)
}
}
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get"
onsubmit="return validateForm(this);">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit">
</div>
</form>
The problem arose because it also validated the send button and because it did not have the termination of the failed id it could not find the item and an error occurred. Then when the error occurred it did not return anything the function and redirect you to the form action page.

form validation problems with jquery / javascript

This is my first real project which involves form validation. I am experiancing a problem which I can not find the solution to.
The objective is this, there is a continue button which will be activated once all the field inputs have been passed as valid. I am going about this by creating seperate variables, all initially set as false, devoted to checking each input field. When the user has entered correct validation data, the variable is set to true.
I then run an if statement to check if all the variables are set to true, and if so, I activate the continue button which, when clicked, slides the next part of the form into the page.
HTML:
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" id="submit" value="CONTINUE">
</div>
</div>
</div>
JAVASCRIPT / JQUERY:
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input",function(){
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility","visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)){
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility","visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility","hidden");
emailValidated = true;
}
})
//name validation check//
nameField.on("input",function(){
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility","visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility","hidden");
nameValidated = true;
}
})
//contact number validation check//
numberField.on("input",function(){
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility","visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility","hidden");
numberValidated = true;
}
})
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
})
at the moment, I am simply using the alert prompt to test if it is working, but it fails.
As mentioned, this is my first real form validation. Any other tips or advice would be greatly appreciated. Thanks for the help in advance.
There were a couple things that I found from copying pasting your snippets of code. 1 there was an ending "})" without a beginning $(document).ready(function(){ ". 2 none of your ".on" statements had an ending semi colon.
Here is my javascript with a small change
$(document).ready(function () {
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input", function () {
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)) {
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility", "hidden");
emailValidated = true;
enableContinue();
}
});
//name validation check//
nameField.on("input", function () {
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility", "visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility", "hidden");
nameValidated = true;
enableContinue();
}
});
//contact number validation check//
numberField.on("input", function () {
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility", "visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility", "hidden");
numberValidated = true;
enableContinue();
}
});
enableContinue = function () {
if (emailValidated && nameValidated && numberValidated) {
$('#submit').prop('disabled', false);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" class="btn btn-primary" id="submit" disabled="disabled" value="CONTINUE">
</div>
</div>
</div>
Your form CONTINUE button becomes enables once all fields have a value. Note: I did not try to improve your javascript any, just made it work.
Right now you synchronically check validation variables at script, so they are all false. You have to asynchronically check them after form submit. Just add event listener to form submit to check variables like this:
document.getElementById('#form').addEventListener('submit', function(){
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
});
Don't forget to set id to your form.
You may be able to save a lot of work if you leverage some of the built in HTML5 form validation. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
This simple example adds a new field every time you submit the form, as long as the existing fields are valid. You would need to test the state of the form to see if you should be adding another section or submitting.
$('form').on('submit', function() {
$(this).find('fieldset').append('<input type="text" required />');
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<input type="text" required />
</fieldset>
<input type="submit" id="submit" value="continue" />
</form>

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