Prevent submission if fields do not match - javascript

I am using JS to check if two fields match but I need a way to disable the submit button if they fail to match and then enable once they do match:
<label>New password:</label><br><input type="password" name="new_password" id="password1"/><br><br>
<label>Confirm password:</label><br><input type="password" name="new_password_check" id="password2" /><br><br>
<p id="validate-status"></p>
$(document).ready(function() {
$("#password2").keyup(validate);
});
function validate() {
var password1 = $("#password1").val();
var password2 = $("#password2").val();
if(password1 == password2) {
$("#validate-status").text("Passwords Match!");
}
else {
$("#validate-status").text("Passwords Do Not Match!");
}
}
UPDATED
<form method="post" action="password_change.inc.php">
<input type="hidden" name="user_id" value="<? echo $_SESSION['user_id']; ?>" />
<label>New password:</label><br><input type="password" name="new_password" id="password1"/><br><br>
<label>Confirm password:</label><br><input type="password" name="new_password_check" id="password2" /><br><br>
<p id="validate-status"></p>
<input id="#submit-button" type="submit" value="Change password" />
</form>
<script>
function validate() {
var password1 = $("#password1").val();
var password2 = $("#password2").val();
if(password1 == password2) {
$("#validate-status").text("Passwords Match!");
$('#submit-button').prop('disabled', false);
}
else {
$("#validate-status").text("Passwords Do Not Match!");
$('#submit-button').prop('disabled', true);
}
}
</script>
I have updated my code as per a kind suggestion below but it will still allow me to post the form without disabling until the fields match...

If your submit button id is "submit", you can do :
$("#submit").prop('disabled', true);​
(you might want to validate on clicking the submit button also)
So you should try something like :
if(password1 == password2) {
$("#validate-status").text("Passwords Match!");
$("#submit").prop('disabled', false);​
}
else {
$("#validate-status").text("Passwords Do Not Match!");
$("#submit").prop('disabled', false);​
}
But I would suggest you to write it this way:
As you are submitting the form, it's better to do the validation on submitting the form, because by calling validate on keyup you will be doing lot of unnecessary work.
<input id="submit" type="submit" value="Change password" onSubmit="return validate();" />
function validate(){
return ($("#password1").val() === $("#password2").val());
}
writing onSubmit=" return validate(); in your form submit button prevents the form from submitting when the validate function returns false. So you don't need to write any other code. This should be enough.

Give both password elements a class and do a .blur().
$('.myClass').blur(function () { value is the same enable submit, else disable });
I would put a check on the submit function as well and if the values are not the same return false and some message saying the passwords don't match

Firstly you need to remove that # from your input id. It would probably make sense to disable it on load as well.
input id="submit-button" type="submit" value="Change password" disabled="true"
Then just set a keyup listener on both password fields
$("#password1, #password2").keyup(function (e) { validate(); });
(Based on your updated code)

Apologies for adding to a 5-year old question, but here is another way of doing it...
<form method="post" action="password_change.inc.php">
<input type="hidden" name="user_id" value="<? echo $_SESSION['user_id']; ?>" />
<label>New password:</label><br><input type="password" name="new_password" id="password1"/><br><br>
<label>Confirm password:</label><br><input type="password" name="new_password_check" id="password2" /><br><br>
<p id="validate-status"></p>
<input id="submit-button" type="submit" value="Change password" />
</form>
<script>
$('#password1, #password2').keyup(validate); // Allows for interchangeable user text - Example, if user types in password1 field, but actually has password2 field with the correct password, user can correct password1 field and things match/validate
function validate() {
var password1 = $("#password1").val();
var password2 = $("#password2").val();
if(password1 == password2) {
$('#validate-status').css({'background' : 'green'});
$('#validate-status').text('Passwords Match');
// Below commented out code works too...
//$('#submit-button').prop('disabled', false);
$('#submit-button').css({'display' : 'block'}); // Bring the submit button back...
}
else {
$('#validate-status').css({'background' : 'red'});
$('#validate-status').text('Passwords do NOT match - Please fix');
// Below commented out code works too...
//$('#submit-button').prop('disabled', true);
$('#submit-button').css({'display' : 'none'}); // Do not display the submit button - user has no choice but to correct passwords and make them match...
}
}
</script>
Fiddle: https://jsfiddle.net/8kLypb7q/1/

You're almost there. Set the disabled property on your submit button (which appears to be missing from your pasted code). Assuming your submit button has an id submit-button:
function validate() {
var password1 = $("#password1").val();
var password2 = $("#password2").val();
if(password1 == password2) {
$("#validate-status").text("Passwords Match!");
$('#submit-button').prop('disabled', false);
}
else {
$("#validate-status").text("Passwords Do Not Match!");
$('#submit-button').prop('disabled', true);
}
}
An optimised version would "cache" the elements like so:
var $password1 = $("#password1"),
$password2 = $("#password2"),
$statusMessage = $("#validate-status"),
$submitButton = $('#submit-button');
function validate() {
if($password1.val() == $password2.val()) {
$statusMessage.text("Passwords Match!");
$submitButton.prop('disabled', false);
}
else {
$statusMessage.text("Passwords Do Not Match!");
$submitButton.prop('disabled', true);
}
}

Related

How can I cancel submit form after password and password confirmation doesn't match

I'm trying to do a registration page for my site and I don't know how to stop users to click submit after the password and confirmation password doesn't match.
I have a function to "alert" if there is no match between the two passwords.
HTML:
<input type="password" name="password" value="" id="password" placeholder="Password">
<input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm Password" onkeyup='check();'/>
span id='message'></span>
JS:
var check = function() {
if (document.getElementById('password').value ==
document.getElementById('confirm_password').value) {
document.getElementById('message').style.color = 'green';
document.getElementById('message').innerHTML = 'Passwords are matching';
} else {
document.getElementById('message').style.color = 'red';
document.getElementById('message').innerHTML = 'Passwords does not match' ;
}
}
I was thinking about boolean function, but I don't know how to call it inside of and how to cancel the submition.
Add a validation function to your <form onsubmit="validate()">
Calling preventDefault on the submit event will prevent the form from actually submitting.
function validate(event) {
if (!passesValidation) event.preventDefault();
}
In your JS, why not put the values into variables? Not necessary but will make for cleaner JS
In that function Id do something like
var password = document.getElementById('password').value
var confrm_password = document.getElementById('confirm_password').value
const button = document.getElementById('button') (Or however you want to target the button, up to you)
and than
button.disabled = (password === confirm_password))
you can disable the button when passwords are not matching
document.getElementById("Button").disabled = false;

Use JavaScript to change the href Tag depending on input field

I want to make the link in this change depending on whether the password is correct. I want to set one password and I only know html and minimal JS. I think I have it set so that when the password is wima it will change the href and allow the link to work. That doesn’t happen. Can I have some help?
function login()
var password = getElementById("password"); {
if (password = "wima") {
getElementById("submit").href = "/pages/home.html";
} else {
getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type=text placeholder="WIMA"><br> Password
<input id="password" type=password placeholder="WIMA"><br>
<a class="button" id="submit" href="#" onclick="login()">
Submit
</a>
</p>
There are a few issues with your JavaScript.
<script language="JavaScript">
function login()
var password = getElementById("password"); // this gets the element, not the value of the element
{ // this curly brace is in the wrong place
if (password = "wima") { // this sets the value of the password var to "wima"
getElementById("submit").href="/pages/home.html";
}
else {
getElementById("submit").href="index.html";
}
}
</script>
Here is your code, cleaned up.
<script language="JavaScript">
function login() {
var password = document.getElementById("password").value;
if (password == "wima") { // use == to compare value
document.getElementById("submit").href="/pages/home.html";
}
else {
document.getElementById("submit").href="index.html";
}
}
</script>
Another issue here is that you shouldn't be changing the href on the element used to execute the login() function.
You could redirect the user to the new page like so:
<script language="JavaScript">
function login() {
var password = document.getElementById("password").value;
if (password == "wima") {
window.location.href="/pages/home.html";
}
else {
window.location.href="index.html";
}
}
</script>
I guess you are doing it wrong if you want to change the href value based upon input type text. You should make a blur/change event on password input text. Based upon password value when user clicks on href he should be redirected accordingly.
Check this out:
function login() {
var _password = document.getElementById("password").value;
if ("wima" == _password) {
document.getElementById("submit").href = "/pages/home.html";
} else {
document.getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type=text placeholder="WIMA">
<br> Password
<input id="password" type=password placeholder="WIMA" onblur="login()">
<br>
<a class="button" id="submit" href="#">
Submit
</a>
</p>
Here is a form validator with a switch.
function validateForm() {
var x = document.forms["myForm"]["password"].value;
switch (x) {
case "":
alert("Name must be filled out");
return false;
break;
case "wima":
return true;
break;
default:
alert("Error: Wrong Password.");
document.location.href = "https://stackoverflow.com/search?q=notloggedin";
// Replace the link above with your error link return
return false;
}
}
<!-- Replace action link with your successful link -->
<form name="myForm" action="https://stackoverflow.com/search?q=login" onsubmit="return validateForm()" method="post">
<input type="password" name="password">
<input type="submit" value="Submit">
</form>
Your password is visible in text if someone inspects the html/javascript. So this method of security is not advised. For basic concepts it is interesting to have a link change based on input. Try this.
<p>
Username
<input id="username" type="text" placeholder="WIMA"><br> Password
<input id="password" type="password" placeholder="WIMA"><br>
<a class="button" id="submit" >
Submit
</a>
</p>
<script>
var password = document.getElementById('password');
password.addEventListener('change', enableLogin);
var submit = document.getElementById('submit');
function enableLogin() {
if (password.value == "wima") { // it is an easy mistake (= or ==)
submit.href = "/pages/home.html";
} else {
submit.removeAttribute('href');
}
}
</script>
A few things happened here:
The value inside a <input> is accessed by .value;
You misplaced the {
getElementById is not a global method it has to be called on the element you want to select in (in your case the document itself)
To test if two values are equal use === in js
function login() {
var password = document.getElementById("password").value;
if (password === "wima") {
document.getElementById("submit").href = "/pages/home.html";
} else {
document.getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type="text" placeholder="WIMA"><br> Password
<input id="password" type="password" placeholder="WIMA"><br>
<a class="button" id="submit" href="#" onclick="login()">
Submit
</a>
</p>

Text obtained with innerHTML dissapear

I have the following code:
function passVerif() {
if (document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
if (document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="button" name="required" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
As you can see, input type is submit. Because of that (page is refreshing after click on button) the text I want to show disappears after refresh.
As I read on other posts, the simple change from submit to button will do the dew.
But I am suspecting that I messed up the return false and return true instructions in all of my functions.
Is this correct? If they are in a logical way I can avoid the page refresh and continue to use submit? At least until all conditions are met and the form is good to go.
In other words, can someone help me to put return false and true in such way that the page will refresh only if all conditions are met.
Thanks a lot, I am not even a noob.
Codes are copied from different sources on the internet. I am at the very beginning of coding road. Please have mercy :)
I would change it to one validation function and have a bool that is returned based on if it has errored or not:
// Just have one validation function
function validate() {
var errorMessage = ''; // build up an error message
var email = document.forms['form'].email.value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (email === "") {
errorMessage += "Email field is empty!<br>";
} else if (!emailFilter.test(email)) { // this can be else if
errorMessage += "Please enter a valid e-mail address!<br>";
}
if (document.forms['form'].pass.value === "") {
errorMessage += "Password field is empty!<br>"
}
if (errorMessage === '') {
return true; // return true as no error message
} else {
document.getElementById('error-message').innerHTML = errorMessage; // show error message and return false
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="submit" name="required" onclick="return validate();">
</form>
</div>
<div id="error-message">
<!-- CAN HAVE ONE ERROR MESSAGE DIV -->
</div>
I tried with your code and I could find the the messages were not getting updated based on the conditions. So I did few modifications to your code to display the message based on which condition fails.
HTML
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br><br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br><br>
<input type="submit" name="required" value="Submit" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
JS
function passVerif() {
messagePV.innerHTML = ("")
if(document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
messageEV.innerHTML = ("")
if(document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
messageV.innerHTML = ("")
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
By initializing the errormessage filed to empty sting u can maintain the fresh set of error messages.
Jsfiddle: https://jsfiddle.net/85w7qaqx/1/
Hope this helps out.

how to check password field with confirm password field

I have written a function in javascript to chek whether both fields are same or not:
javascript code:
function validate();{
var x= getElementByName("password");
var y= getElementByName("retype_password");
if(x==y) return;
else alert("password not same");
HTML code: HOW CAN I CALL THE ABOVE WRITTEN FUNCTION IN THE HTML CODE
password : <input type= "password" name="password"> <br><br>
retype password : <input type="password" name="retype_password" > <br><br>
thanks in advance
password : <input type= "password" id="password" onblur="validate()"> <br><br>
retype password : <input type="password" id="retype_password" onblur="validate()"> <br><br>
<script>
function validate() {
var x= document.getElementById("password");
var y= document.getElementById("retype_password");
if(x.value==y.value) return;
else alert("password not same");
}
</script>
Please be careful with method names in JavaScript. The correct method for picking the element by name is document.getElementsByName which returns a NodeList. So in order to get the first field with the required name you should treat the result as array:
function validate() {
var x = document.getElementsByName('password')[0].value,
y = document.getElementsByName('retype_password')[0].value;
if (x === y) {
return true;
}
alert('password not same');
return false;
}
To make the solution work correctly you have to bind the validation function as a <form> submit event (as an example):
var form = document.getElementById('myform');
form.addEventListener('submit', function() {
return validate();
}, false);
Or shorter as:
document.getElementById('myform').addEventListener('submit', validate, false);
If you don't have a form and use some button-like elements, you may bind a click event, e.g.:
var mybutton = document.getElementById('mybutton');
mybutton.addEventListener('click', function() {
if ( validate() ) {
// do AJAX request or whatever...
}
}, false);
Their are many ways to call this function.
You can add a new button :
<input type = 'button' value = 'validate' onclick = 'validate()' />
Or call the function when the focus on the text field is out :
<input type="password" name="retype_password" onblur = 'validate()' > <br><br>
Their are other ways to do (onkeydown, onchange...) check JS events to learn more : http://www.w3schools.com/jsref/dom_obj_event.asp
Right code from #VisioN :
function validate(event) {
var x = document.getElementsByName('password')[0].value,
y = document.getElementsByName('retype_password')[0].value;
if (x === y) {
return true;
} else {
alert('password not same');
event.preventDefault();
return false;
}
}
Add a onclick="validate(event);" attribute on the submit button.
(if validate return false, prevent the event from bubbling with event.preventDefault();).
EDIT
Maybe it is better tyo bind it to onSubmit event.
<form onsubmit="validate(event)">
Apolo
You have to use getElementById instead of getElementByName
Javascript:
function validate() {
var x = getElementById("password").value;
var y = getElementById("retype_password").value;
if(x==y) {
return true;
} else {
alert("password not same");
return false;
}
}
and html:
<form onsubmit="return validate();" action="submit_path" >
<input type= "password" id="password" name="password">
<input type= "password" id="retype_password" name="retype_password">
<input type="submit" name="submit" value="Submit" >
</form>
Here is an easier way by using class:
password : <input type= "password" class="passwords" name="password"> <br><br>
retype password : <input type="password" class="passwords" name="retype_password" > <br><br>
In your javascript:
var passwords = document.getElementsByClassName("passwords");
function validate(){
var first = passwords[0].value;
var second = passwords[1].value;
if(first != second){
//Invalid
} else{
//Valid
}
}

form validation error

I have little problem with form and I am using js for validation.
Here is my form code.
<form method="get" onkeydown="checkEnter()" action="emailform.php" id="signupform" name="subscribe">
<input name="email" id="email" type="text" value="Enter Email for Updates" onfocus="if(this.value=='Enter Email for Updates'){this.value=''};" />
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
id signupform I am using for validation and submit the form is on pressing enter button.
But there is problem when put signupform then my validation start working fine and when I enter correct email it's show me error and when I remove the signupform id then my form submission work fine without validation.
Here is my JS code for id signupform.
function SubscribeForm() {
$('#signupform').submit(function () {
$('.email').removeClass('error')
$('em.error').remove();
var error = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($.trim($('.email').val()) == '') {
$(this).append('<em class="error">Please enter your email address.</em>');
$(this).addClass('error');
error = true;
} else if (!emailReg.test(jQuery.trim($('.email').val()))) {
$(this).append('<em class="error">Please enter a valid email address</em>');
$(this).addClass('error');
error = true;
}
if (!error) {
$("#submit", this).after('<span id="form_loading"></span>');
var formValues = $(this).serialize();
$.post($(this).attr('action'), formValues, function (data) {
$("#signupform").before(data);
});
$(':input[type="text"]').attr('value', '');
}
return false
});
}
change
return false
to
return error;
it is causing problem.
change
return false;
to
return !error;
Also, add css class "email" to input email field, or change jquery to selector code ".email" to "#email"
Also a possible solution, if you don't need to support the old browser: placeholder.
<input placeholder="Enter email" type="text"... />
Thanks for your help Guys. i just put this and now working fine.
$('#signupform').submit(function(){
$('.email').removeClass('error')
$('em.error').remove();
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
sEmail = document.getElementById('email').value;
if (filter.test(sEmail)) {
return true;
}
else {
if(sEmail == '')
{
$(this).append('<em class="error">Please enter your email address</em>');
$(this).addClass('error');
}
else
{
$(this).append('<em class="error">Please enter a valid email address</em>');
$(this).addClass('error');
}
return false;
}
});
});

Categories

Resources