password mismatch alert javascript on onkeypress - javascript

I want to check whether confirm password matches with password or not, through onkeypress() function. It's not working.. Some of the part working like password length must be 6 character. But, I'm having problem.. when i'm typing value for confirm password.. it is showing div error message even after when it matches with the password value which i entered in password text. Please help. Here is my code.
<input type='password' class='Register-textbox Password' name="Password" onkeypress="RegistrationValidation()">
<input type='password' class='Register-textbox ConfirmPassword' name="ConfirmPassword" onkeypress="RegistrationValidation()">
<div class="ShowPasswordNotMatchesError" style="display:none;">
* Password Mismatch
</div>
<script>
function RegistrationValidation()
{
var PasswordVal=$('.Password').val();
var ConfirmPasswordVal=$('.ConfirmPassword').val();
if(PasswordVal!=ConfirmPasswordVal)
{
$('.ShowPasswordNotMatchesError').show();
}
}
</script>

When you are using jQuery, please make use of those functions. I have made the following changes:
Made the code unobtrusive.
Checked for the correctness on blur().
Checked only if the user has entered something.
Removed unnecessary braces.
Added reverse condition.
Try this way:
$(function () {
$(".Register-textbox").blur(function () {
var PasswordVal=$('.Password').val();
var ConfirmPasswordVal=$('.ConfirmPassword').val();
if(PasswordVal != ConfirmPasswordVal && ConfirmPasswordVal.length > 0 && PasswordVal.length > 0)
$('.ShowPasswordNotMatchesError').show();
else
$('.ShowPasswordNotMatchesError').hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type='password' class='Register-textbox Password' name="Password" />
<input type='password' class='Register-textbox ConfirmPassword' name="ConfirmPassword" />
<div class="ShowPasswordNotMatchesError" style="display:none;">
* Password Mismatch
</div>

Related

Using submit type but IF statement does not work

I am trying to make a very simple login page for a website I created and I am having issues with the submit button. I got the submit button to work fine if I use a "button" type in HTML however the Enter key does not work then. I discovered if I use a "submit" type, the Enter button and the mouse click will work however... the button now goes over my IF statement, straight to my Else statement. Any help would be appreciated.
HTML form:
<form>
<label for="pswd">ENTER PASSWORD</label>
<br>
<input class="box" type="password" id="pswd">
<br>
<input class="confirm" type="submit" value="SUBMIT" onclick="checkPswd();" />
</form>
JS code:
function checkPswd() {
var confirmPassword = "08012020";
var password = document.getElementById("pswd").value;
if (password == confirmPassword) {
window.location = "index.html";
} else {
alert("Password is incorrect, Please try again.")
}
}
Again, thank you in advance...
The key is returning false after calling your function, so the page redirect is not triggered by the input submission:
function checkPswd() {
let confirmPassword = "08012020";
let password = document.getElementById("pswd").value;
if (password === confirmPassword) {
alert("CORRECT!");
} else{
alert("Password is incorrect, Please try again.")
}
}
<form>
<label for="pswd">ENTER PASSWORD</label>
<br>
<input class="box" type="password" id="pswd">
<br>
<input class="confirm" type="submit" value="SUBMIT" onclick="checkPswd(); return false;" />
</form>
I would like to add that performing client-side password checking is very insecure since the source code can easily be inspected, so if you are hoping to use this in a real website I would suggest you consider a different approach!

Trying to verify passwords are matching using html and javascript

I have a form that is supposed to register a user and I have two inputs for passwords that are supposed to be the same. I use html for the form and javascript to check if both inputs are matching. The code I'm using doesn't work though because even if the passwords are different, the user data is still sent to my console when the form shouldn't be able to submit in the first place. These are portions of my html file.
<form id="registration-info" method="POST" action="/registration" onsubmit="return validatePassword();">
....
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" required>
<div class="invalid-feedback">
Please enter a password.
</div>
</div>
<div class="mb-3">
<label for="repeat_password">Repeat Password</label>
<input type="password" class="form-control" name="repeat_password" id="repeat_password"required>
<script language='javascript' type='text/javascript'>
var password = document.getElementById("password")
, repeat_password = document.getElementById("repeat_password");
function validatePassword(){
if(password.value != repeat_password.value) {
document.repeat_password.setCustomValidity("Passwords Don't Match");
} else {
document.repeat_password.setCustomValidity('');
}
}
</script>
</div>
You have a few mistakes there you'll need to fix up.
Use a JavaScript event listener and remove document..
form = document.getElementById("registration-info");
form.onclick = function() {
var password = document.getElementById("password");
var repeat_password = document.getElementById("repeat_password");
if(password.value != repeat_password.value) {
repeat_password.setCustomValidity("Passwords Don't Match");
} else {
document.repeat_password.setCustomValidity('');
}
}
You do not need to use document. when references variables you have set. Using a JavaScript event listener helps you write clean code, that separates UI and logic.

validating a form using jQuery

I've tried, I've researched, and I still can't figure out how to validate this form using jQuery. I've even tried to check out the jQuery API and I had no luck with it. This shouldn't be as hard as it seems. There are a few id's that i'm not using yet because I want to get what I have so far working before I continue. The best I could find for validating emails is just straight up JavaScript. Here's my code.
$(document).ready(function(){
$("#sendForm").click(function(){
var validForm=true; //set valid flag to true, assume form is valid
//validate customer name field. Field is required
if($("#custName").val()) {
$("#custNameError").html(""); //field value is good, remove any error messages
} else {
$("#custNameError").html("Please enter your name.");
validForm = false;
}
//validate customer phone number. Field is required, must be numeric, must be 10 characters
var inPhone = $("#custPhone").val(); //get the input value of the Phone field
$("#custPhoneError").html(""); //set error message back to empty, assume field is valid
if(!inPhone) {
$("#custPhoneError").html("Please enter your phone number.");
validForm = false;
} else {
//if( !$.isNumeric(inPhone) || Math.round(inPhone) != inPhone ) //if the value is NOT numerice OR not an integer. Rounding technique
if( !$.isNumeric(inPhone) || (inPhone % 1 != 0) ) //if the value is NOT numerice OR not an integer. Modulus technique
{
$("#custPhoneError").html("Phone number must be a number.");
validForm = false;
} else {
if(inPhone.length != 10) {
$("#custPhoneError").html("Phone number must have 10 numbers");
validForm = false;
}
}
}
//ALL VALIDATIONS ARE COMPLETE. If all of the fields are valid we can submit the form. Otherwise display the errors
if(validForm) {
//all values are valid, form is good, submit the form
alert("Valid form will be submitted");
//$("#applicationForm").submit(); //SUBMIT the form to the server
} else {
//form has at least one invalid field
//display form and associated error messages
alert("Invalid form. Display form and error messages");
}
}); //end sendform.click
}); //end .ready
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
label {
width:150px;
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2></h2>
<h3>Form Validation Project - Complaint Form</h3>
<form id="form1" name="form1" method="post" action="">
<p>Please enter the following information in order to process your concerns.</p>
<p>
<label for="custName">Name:</label>
<input type="text" name="custName" id="custName" />
<span id="custNameError" class="errorMsg"></span>
</p>
<p>
<label for="custPhone">Phone Number: </label>
<input type="text" name="custPhone" id="custPhone" />
<span id="custPhoneError" class="errorMsg"></span>
</p>
<p>
<label for = "email">Email:</label>
<input type = "text" name = "emailAdd" id = "emailAdd" />
<span id = "emailError" class = "emailError"></span>
</p>
<p>Please Select Product Group:</p>
<p>
<label>
<input type="radio" name="custProducts" value="books" id="custProducts_0" />
Books
</label>
<br />
<label>
<input type="radio" name="custProducts" value="movies" id="custProducts_1" />
Movies
</label>
<br />
<label>
<input type="radio" name="custProducts" value="electronics" id="custProducts_2" />
Consumer Electronics
</label>
<br />
<label>
<input type="radio" name="custProducts" value="computer" id="custProducts_3" />
Computer
</label>
<br />
</p>
<p>Description of problem: (Limit 200 characters)</p>
<p>
<label for="custComplaint"></label>
<textarea name="custComplaint" id="custComplaint" cols="45" rows="5"></textarea>
</p>
<p>
<input type="submit" name="button" id="button" value="File Complaint" />
<input type="reset" name="button2" id="button2" value="Reset" />
</p>
</form>
<p> </p>
$("#button").click(function(e){
e.preventDefault(); // you need to stop the initial event to have a chance to validate
var validForm=true;
// etc...
You can use jquery.validate.js to validate your forms , it will overcome all your manual efforts to create the validation rules also it is providing the various predefined rules like required,email, minlength and maxlength, etc. So, it will be easier for you to achieve what you need very easily.
https://jqueryvalidation.org/
I have a simple jquery form validation and submission package - see if that's of any help - it's easy to install and you can customise quite a few things: https://github.com/sebastiansulinski/ssd-form
Just to get you started, your submit control in the html has id "button", so you should use $('#button').click, not $('#sendForm').click.
Also, if you want to stay on the page (like to do validations, show errors, etc), you have to prevent the form from submitting automatically when the button is clicked. There are lots of ways to do this, but the easiest way is to just change your button type from submit to button. Ie, replace this:
<input type="submit" name="button" id="button" value="File Complaint" />
with this:
<input type="button" name="button" id="button" value="File Complaint" />
------
That should get you started, at least your code will run, you can use console.log to debug, etc. Good luck.
UPDATE
I should add that if you take my advice, the form will never submit on it's own - that is good if some validation fails and you want to stay on the page and give some error feedback to the user.
When you do want the form to submit, you have to make it happen yourself. Again, there are lots of ways to do this, but the simplest one is probably:
$('#form1').submit();

Validating Password and Retype Password

I am having two textboxes like this :
<p>
<input type="text" name="NPassword" placeholder="New Password"/></p>
<input type="text" name="RNPassword" placeholder="Retype New Password"/>
Now,what i want is that on every keypress of Retype New Password It should check if both are same or not.If yes then in green color display it on right side of RNPassword,Otherwise in red color display that both are not same and also disable the submit button of the page.How this can be done please help.
Try this demo: ==> http://jsfiddle.net/uP8Q2/
Another demo = http://jsfiddle.net/ALk9Z/
disable button demo http://jsfiddle.net/K2Xdc/
2 things to start with:
use type=password ~> http://www.w3.org/TR/html-markup/input.password.html
use .keyup() API: http://api.jquery.com/keyup/
Also next time add your JS code with the post :) rest should fit the need.
code
HTML
<p>
<input type="password" name="NPassword" placeholder="New Password" id="txtNewPassword" />
</p>
<input type="password" name="RNPassword" placeholder="Retype New Password" id="txtConfirmPassword" onChange="isPasswordMatch();" />
<div id="divCheckPassword"></div>
JS
function isPasswordMatch() {
var password = $("#txtNewPassword").val();
var confirmPassword = $("#txtConfirmPassword").val();
if (password != confirmPassword) $("#divCheckPassword").html("Passwords do not match!");
else $("#divCheckPassword").html("Passwords match.");
}
$(document).ready(function () {
$("#txtConfirmPassword").keyup(isPasswordMatch);
});
Disable button demo code
$('#hulk').prop('disabled' , true);
$('#txtConfirmPassword').on('keyup', function () {
var password = $("#txtNewPassword").val();
var confirmPassword = $("#txtConfirmPassword").val();
if (password != confirmPassword) {
$("#divCheckPassword").html("Passwords do not match!");
} else {
$("#divCheckPassword").html("Passwords match.");
$('#hulk').prop('disabled' , false);
}
});
If you want to check that before submit you can do that in following way
With plain Jquery:
<p>
<input type="text" name="NPassword" id="first" placeholder="New Password"/></p>
<input type="text" name="RNPassword" id="second" placeholder="Retype New Password"/>
<span id="error" class="hidden">Not Matched"</span>
And then:
EDIT ONCHANGE
$('#second').keyup(function(e){
if($('#first').val() !== $('#second').val()){
$('#error').removeClass('hidden');
return false;
}else{
$('#error').addClass('hidden');
}
});
http://liveweave.com/yVXnIF
If you use KnockoutJs or AngularJs those have ability to bind verification in model itself.

How to Stop Submitting Empty Fields in Input

I am using a subscribe news letter script by using MySQL and PHP. When the user enters the e-mail and clicks the button the e-mail is added to database.
The issue is that while clicking the button without entering an e-mail, the data base is updating with an empty record. How can I stop submitting the empty fields and force the user to enter an e-mail?
Here is my HTML:
<form id="myForm" action="update.php" method="post">
<input type="hidden" name="action" value="update" />
<input type="text" name="email" id="email" value="Enter your email here" onfocus="if (this.value == 'Enter your email here') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Enter your email here';}" onwebkitspeechchange="this.value = this.value.replace('Enter your email here','')"; style=" color:#999; font-size:1em;width:200px; font-style:italic; font-family:"Times New Roman", Times, serif;"/>
<input class="button" type="image" src="rss.png" />
</form>
Sounds to me like you need to do some form validation before you take the user input and insert it into your database. It's dangerous to do as you're doing.
Why not use one of the many plugins out there:
http://www.queness.com/post/10104/powerful-javascript-form-validation-plugins
This is a useful tutorial on using the jquery validation plugin: http://docs.jquery.com/Plugins/Validation
Ignore the styling in their example and focus on the core aspects. In your case, the most useful line is:
<input id="cemail" name="email" size="25" class="required email" />
Roughly, you would need to do something like..
var form = $('#mtForm');
$('input').change(function(){
if($((this).val() == ''){
form.unbind('submit').submit(function(){
return false;
});
}
else{
form.unbind('submit');
}
})
You should change the value attribute of your email field to a placeholder attribute. The onfocus, onwebkitspeechchange and onblur code can be removed from the email input tag.
You can use something like this to check for a blank field if that's the only type of validation you're after (below is written with jQuery).
$(function(){
$('#myForm').submit(function(e){
if ($('#email').val().trim() == "") {
// some sort of notification here
e.preventDefault();
return false;
}
});
});
​
Ideally, you would validate the form on the client side (javascript/JQuery) as well as the server side (php).
For clarity I will remove the inline code on your input box to get this:
<input type="text" name="email" id="email" value="Enter your email here" />
Note - You may use
placeholder='Enter your email here'
to get the prompt in your input box.
Client side validation using HTML5
Make a required field with email format validation:
<input type="email" name="email" id="email" value="Enter your email here" required="required"/>
Client side validation using javascript/JQuery - example.js
JQuery:
$('#email').bind('blur', function() {
if (!validateEmail($(this).val()) {
// Add errors to form or other logic such as disable submit
}
});
function validateEmail($email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test($email);
}
}
Server side validation - update.php
// Require the email
if (empty($_POST['email'])) {
$error_message = 'You must enter an email!';
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error_message = 'Invalid email format. Example: example#example.example';
} else { // If no errors, continue processing the form
// process the form, enter email
}
The HTML5 alone will prevent submission of the form, however only more recent browsers support HTML5.
Hope this is helpful!

Categories

Resources