Combining two validations in jQuery for password field - javascript

I have a signup form, and I am using a 3rd party library to validate the inputs. This library provides very nice and cool effects for validation, but I need to do another verification to make sure the password and confirm password are matching. how can I do that via jQuery? Here is my code:
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" />
</div>
<div class="form-group">
<label>Retype Password</label>
<input type="password" class="form-control" name="password2" />
</div>
and jQuery part:
$('#registrationForm').formValidation({
framework: 'bootstrap',
fields: {
password: {
validators: {
notEmpty: {
message: 'The password is required'
}
}
},
password2: {
validators: {
notEmpty: {
message: 'Password conformation is required'
},
equalTo: {
field: 'password',
message: 'The password cannot be the same as username'
}
}
}
}
});
What should I put instead of the question marks, to address my issue? Or maybe I am completely wrong with the syntax?

Working Fiddle
Html :
<form id="formCheckPassword">
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" id="password" />
</div>
<div class="form-group">
<label>Retype Password</label>
<input type="password" class="form-control" name="cfmPassword" id="cfmPassword" />
</div>
<input type="submit" value="submit" />
</form>
and Jquery Rules :
$("#formCheckPassword").validate({
rules: {
password: {
required: true,
minlength: 6,
maxlength: 10,
},
cfmPassword: {
equalTo: "#password",
minlength: 6,
maxlength: 10
}
},
messages: {
password: {
required: "the password is required"
}
}
});
Update as per request :
$('#RegistrationForm').formValidation({
framework: 'bootstrap',
fields: {
password: {
validators: {
identical: {
field: 'confirmPassword',
message: 'The password and its confirm are not the same'
}
}
},
confirmPassword: {
validators: {
identical: {
field: 'password',
message: 'The password and its confirm are not the same'
}
}
}
}
});

I don't see it working in that syntax. If you want to do it via jQuery (as you mentioned), you can simply check the values:
var password1 = $('input[name=password]').val();
var password2 = $('input[name=password2]').val();
var match = password1 == password2

Related

jQuery validation plugin is validating only specific form fields

I am trying basic client-side form validation using jQuery validation plugin.I have a basic sign up form, if I click on a button to create an account with all fields empty(just for testing), I am getting nice error messages as expected on all form fields except for only one field for inputting cellphone number. I have downloaded the code from the internet and this is the only field I have added.I am using Xampp, Things became even more strange after I moved all files to another computer and try to test the same validation, Guess what? it's no longer working as expected for all fields. This problem has been frying my brains, any help I will be grateful below is the code
HTML
<h2 class="form-signin-heading">Sign Up</h2><hr />
<div id="error">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" name="user_name" id="user_name" />
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email address" name="user_email" id="user_email" />
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Cellphone" name="user_cellphone" id="user_cellphone" />
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name="password" id="password" />
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Retype Password" name="cpassword" id="cpassword" />
</div>
<hr />
<div class="form-group">
<button type="submit" class="btn btn-default" name="btn-save" id="btn-submit">
<span class="glyphicon glyphicon-log-in"></span> Create Account
</button>
</div>
</form>
JS
$('document').ready(function()
{
/* validation */
$("#register-form").validate({
rules:
{
user_name: {
required: true,
minlength: 3
},
user_cellphone: {
required: true,
number: true
},
password: {
required: true,
minlength: 8,
maxlength: 15
},
cpassword: {
required: true,
equalTo: '#password'
},
user_email: {
required: true,
email: true
}
},
messages:
{
user_name: "Enter a Valid Username",
user_cellphone:{
required: "Provide a phone number",
number: "Phone Needs To Be a number"
},
password:{
required: "Provide a Password",
minlength: "Password Needs To Be Minimum of 8 Characters"
},
user_email: "Enter a Valid Email",
cpassword:{
required: "Retype Your Password",
equalTo: "Password Mismatch! Retype"
}
},
submitHandler: submitForm
});
/* validation */
/* form submit */
function submitForm()
{
var data = $("#register-form").serialize();
$.ajax({
type : 'POST',
url : 'register.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#btn-submit").html('<span class="glyphicon glyphicon-transfer"></span> sending ...');
},
success : function(data)
{
if(data==1){
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> Sorry email already taken !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
}
else if(data=="registered")
{
$("#btn-submit").html('Signing Up');
setTimeout('$(".form-signin").fadeOut(500, function(){ $(".signin-form").load("successreg.php"); }); ',5000);
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
}
}
});
return false;
}
/* form submit */
Below is a snapshot of the form, I cant really figure out where is the problem.
You're declaring the number rule, but your corresponding message is assigned to the minlength rule...
rules: {
user_cellphone: {
required: true,
number: true
},
....
},
messages: {
user_cellphone: {
required: "Provide a phone number",
minlength: "Phone Needs To Be a number"
},
....
And document should not be in quotes...
$(document).ready(function() {...
Working DEMO: http://jsfiddle.net/bh5g0wfe/
Side note: You may want to read this too...
Dangerous implications of Allman style in JavaScript

JS validation doesn't run after I enter a valid input and submit the form with rest of the input fields empty

I am developing a web directory with a form on one of its pages. JS validation plug in is used. While submitting the form without filling any Input fields, the form throws errors below each input field as expected! But submitting the form with just one input box filled in refreshes the current page as the action value is set to current page with PHP codes in it, instead of staying on the same page to continue to throw errors for the rest of the fields that are yet to be filled in! I have searched online to find nothing useful in figuring out what is wrong with the script. Could anyone here please look into the code below and recommend the best solution? Thanks.
$(document).ready(function() {
$("#userForm").validate({
rules: {
cname: {
required: true,
lettersonly: true,
minlength: 3
},
cemail: {
required: true,
email: true
},
cphone: {
required: true,
number: true,
minlength: 10,
maxlength: 10
},
cbusiness: {
required: true,
url: true
},
cbcategory: {
required: true,
minlength: 6
},
curl: {
required: true,
minlength: 6
},
},
messages: {
cname: "Please enter your name",
cemail: "Please enter a valid email address",
cphone: {
required: "Please enter your phone number",
number: "Please enter only numeric value"
},
cbusiness: {
required: "Please enter your business",
},
cbcategory: {
required: "Please enter a business category",
},
curl: {
required: "Please enter the URL to your website",
},
}
});
});
The form is as below.
<form action="" method="post" name="userForm" id="userForm">
<input type="text" name="cname" id="cname" placeholder=" Your Name">
<input type="text" name="cemail" id="cemail" class="email" placeholder="Your Email">
<input type="text" name="cphone" id="cphone" placeholder="Your Phone">
<input type="text" name="cbusiness" id="cbusiness" class="email" placeholder=" Your Business">
<input type="text" name="cbcategory" id="cbcategory" placeholder="Business category">
<input type="text" name="curl" id="curl" class="email" placeholder="URL"><br>
<label for='message'>Enter the code in the box below : </label>
<img src="captcha.php?rand=<?php echo rand();?>" id='captchaimg'>
<input type="text" id="captcha_code" name="captcha_code">
<input type="submit" name="Submit" id="Submit" value="Submit" class="button1"><br>
Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh.
</form>
Assuming you have included the validation libraries corectly, you will have to set messages for all of the validation types like:
messages: {
cname: {
required: "Please enter your name",
lettersonly: "Letters only",
minlength: "Min length 3 required"
},
cemail: {
required: "Please enter a valid email address",
email: "Invalid email"
}
}
Working JSFIDDLE.
You have to include the plugin files something like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
UPDATE:
After discussing with OP on chat, we came to the conclusion that the plugin files had to be included correctly and there was an incompatibility between the jQuery version(v 1.7.1) he used and the plugin version(v 1.16.0). So we had to add a custom method for lettersonly.
The code for custom method:
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");

Express: jQuery Validation not working

I'm creating a web application using Express and Jade. I want to validate a form using jQuery Validation. It does not give any errors, but when I insert wrong values in the form, it does not complain either. It just sends the data to the Express server.
This is my form:
form.form-horizontal(#signupForm, method='post', action='')
.form-group
label.col-sm-2.control-label(for='firstName')
| First Name:
.col-sm-10
input.form-control( #firstName,
type='text',
placeholder='John',
name='firstName')
.form-group
label.col-sm-2.control-label(for='lastName')
| Last Name:
.col-sm-10
input.form-control( #lastName,
type='text',
placeholder='Doe',
name='lastName')
.form-group
label.col-sm-2.control-label(for='password')
| Password:
.col-sm-10
input.form-control( #password,
type='password',
placeholder='Password (minimum 8 characters)',
name='password')
.form-group
label.col-sm-2.control-label(for='confirmPassword')
| Confirm Password:
.col-sm-10
input.form-control( #confirmPassword,
type='password')
.form-group
.col-sm-2.control-label
button.btn.btn-default(type='submit')
| Sign Up!
This is the rendered HTML:
<form #signupform="" method="post" action="" class="form-horizontal">
<div class="form-group">
<label for="firstName" class="col-sm-2 control-label">First Name:</label>
<div class="col-sm-10">
<input #firstname="" type="text" placeholder="John" name="firstName" class="form-control">
</div>
</div>
<div class="form-group">
<label for="lastName" class="col-sm-2 control-label">Last Name:</label>
<div class="col-sm-10">
<input #lastname="" type="text" placeholder="Doe" name="lastName" class="form-control">
</div>
</div>
...
<div class="form-group">
<div class="col-sm-2 control-label">
<button type="submit" class="btn btn-default">Sign Up!</button>
</div>
</div>
</form>
This is my JavaScript file:
$(document).ready( function() {
$('#signupForm').validate({
rules: {
firstName: {
required: true
},
lastName: {
required: true
},
password: {
required: true,
minlength: 8
},
confirmPassword: {
required: true,
equalTo: '#password'
}
},
messages: {
firstName: {
required: 'This field is required!'
},
lastName: {
required: 'This field is required!'
},
password: {
required: 'This field is required!',
minlength: 'This password is too short!'
},
confirmPassword: {
required: 'This field is required!',
equalTo: 'This password is not the same!'
}
}
});
});
At a first glance, your id's should look like this:
"lastName": { required: 'This field is required'}
Edit
Seeing your html, your renderd input had a problem with the Id's.
<input #lastname=""
should be
<input id="lastname">
The same goes for your form id.
Edit
As mentioned below, the name attribute is used for validation targeting.

I can not submit my bootstrap form

I have this form to register my users in my website:
<div class="pages_container">
<form id="registerForm" method="post" class="form-horizontal">
<div class="form-group">
<label class="col-lg-3 control-label">Full name</label>
<div class="col-lg-3">
<input type="text" class="form-control" name="firstName" placeholder="First name" />
</div>
<div class="col-lg-3">
<input type="text" class="form-control" name="lastName" placeholder="Last name" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Username</label>
<div class="col-lg-6">
<input type="text" class="form-control" name="username" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Password</label>
<div class="col-lg-6">
<input type="password" class="form-control" name="password" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Retype password</label>
<div class="col-lg-6">
<input type="password" class="form-control" name="confirmPassword" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email address</label>
<div class="col-lg-6">
<input class="form-control" name="email" type="email" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Phone number</label>
<div class="col-lg-6">
<input type="text" class="form-control" name="phone" />
</div>
</div>
<div class="form-group">
<div class="col-lg-6 col-lg-offset-3">
<button type="submit" class="btn btn-primary btn-lg btn-block">Register</button>
</div>
</div>
</div>
</form>
</div>
and I use this JQuery to validate the form and then submit it to a PHP Page to be stored in MySQL Database :
$(document).ready(function(){
//To validate the registration form and save its value after validation
$('#registerForm').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
firstName: {
validators: {
notEmpty: {
message: 'The first name is required'
},
stringLength: {
min: 2,
message: 'The first name must be at least 2 characters long'
},
regexp: {
regexp: /^[a-z\s]+$/i,
message: 'The first name can consist of alphabetical characters and spaces only'
}
}
},
lastName: {
validators: {
notEmpty: {
message: 'The last name is required'
},
stringLength: {
min: 2,
message: 'The last name must be at least 2 characters long'
},
regexp: {
regexp: /^[a-z\s]+$/i,
message: 'The last name can consist of alphabetical characters and spaces only'
}
}
},
username: {
message: 'The username is not valid',
validators: {
notEmpty: {
message: 'The username is required and cannot be empty'
},
stringLength: {
min: 6,
max: 30,
message: 'The username must be more than 6 and less than 30 characters long'
},
regexp: {
regexp: /^[a-zA-Z0-9]+$/,
message: 'The username can only consist of alphabetical and number'
},
different: {
field: 'password',
message: 'The username and password cannot be the same as each other'
},
remote: {
message: 'The username is not available',
url: 'include-ajax/username_or_email_availablitiy.php',
data: {
type: 'username'
}
}
}
},
password: {
validators: {
notEmpty: {
message: 'The password is required and cannot be empty'
},
different: {
field: 'username',
message: 'The password cannot be the same as username'
},
stringLength: {
min: 8,
message: 'The password must have at least 8 characters'
},
identical: {
field: 'confirmPassword',
message: 'The password and its confirm are not the same'
}
}
},
confirmPassword: {
validators: {
notEmpty: {
message: 'The password is required and cannot be empty'
},
different: {
field: 'username',
message: 'The password cannot be the same as username'
},
stringLength: {
min: 8,
message: 'The password must have at least 8 characters'
},
identical: {
field: 'password',
message: 'The password and its confirm are not the same'
}
}
},
email: {
validators: {
notEmpty: {
message: 'The email is required and cannot be empty'
},
emailAddress: {
message: 'The input is not a valid email address'
},
remote: {
message: 'The email is not available',
url: 'include-ajax/username_or_email_availablitiy.php',
data: {
type: 'email'
}
}
}
},
phone: {
validators: {
notEmpty: {
message: 'The phone number is required'
},
digits: {
message: 'The phone number can contain digits only'
},
stringLength: {
min: 11,
max: 11,
message: 'The phone number must be 11 digits'
}
}
},
submitHandler: function(form) { // <- only fires when form is valid
$.ajax({
type: 'POST',
url: 'include-ajax/check_and_save_registration_form.php',
data: $(form).serialize(),
success: function() {alert('test');
$(form).fadeOut(500, function(){
$(form).html("USER DONE!").fadeIn();
});
}
}); // <- end '.ajax()'
return false; // <- block default form action
}
}
});
});
The validation process is working perfectly but the problem is after clicking the submit button I get a javascript error in my console Uncaught TypeError: Cannot read property 'attr' of null and this error is pointing to bootstrapValidator.min.js:12 .
To be honest this is my first bootstrap code so I do not understand the submitHandler so much .
What is the arg form where did we get it should we pass this instead ?
and what is the reason of that error did the script see the form or not ?

jquery confirm password validation

I am using jquery for form validation. Rest is well except the confirm password field. Even when the same password is typed, the Please enter the same password. is not removed.
My script is:
<script type="text/javascript">
$(document).ready(function() {
$("#form1").validate({
rules: {
password: {
required: true, minlength: 5
},
c_password: {
required: true, equalTo: "#password", minlength: 5
},
email: {
required: true, email: true
},
phone: {
required: true, number: true, minlength: 7
},
url: {
url: true
},
description: {
required: true
},
gender: {
required: true
}
},
messages: {
description: "Please enter a short description.",
gender: "Please select your gender."
}
});
});
-->
</script>
And inside the form tag:
<div class="form-row"><span class="label">Password</span><input type="password" name="password" class="required" id="password" /></div>
<div class="form-row"><span class="label">Confirm Password</span><input type="password" name="c_password" id="c_password" /></div>
Any suggestion?
Would be much thankful for the help.
Your fields doesn't have the ID property.
In jQuery the "#password" selector means "the object that has an id property with value 'password'"
Your code should look like this:
<input type="password" name="password" id="password" class="required"/>
<input type="password" id="password" class="nomal required error" value="" name="cpassword">
<input type="password" equalto="#password" class="nomal required error" value="" name="cpassword">
Be sure that your password's input text has id 'password'
rules: {
isn't closed. Put another } after:
messages: {
description: "Please enter a short description.",
gender: "Please select yor gender."
}
This is as well as the answer about the element ID's.
Be sure that no other input with tag id='password' in that same page.
I came across some issues when using camelCase id's for the password inputs. I finnally got it working with different 'name' and 'id'.
<input type="password" id="pass" placeholder="New password" name="newPassword">
<input type="password" id="pass2" placeholder="New password" name="repeatNewPassword">
<input type="email" id="inputNewEmail" name="newEmail" placeholder="New email">
<input type="email" id="repeatNewEmail" name="repeatNewEmail" placeholder="New email>
Then in the JS:
rules: {
newPassword: {
minlength: 6
},
repeatNewPassword: {
minlength: 6,
equalTo: "#pass"
},
newEmail: { email: true},
repeatNewEmail: {email: true, equalTo: '#inputNewEmail'},
}
So refer to the input field by its 'name' but define equalTo deppendency using 'id'. I'm not sure about the camelCase issue, for the email inputs it worked, but exactly same nomenclature with password inputs didn't work, according to my experience
if($("#newpassword").val()!== ($("#conformpassword").val())){
$('#newpasswordId').html('<font color="red">Your password does not match</font>');
$("#newpassword").val('');
$("#conformpassword").val('');
$('#newpassword').css("border", "#FF0000 solid 1px")
$('#conformpassword').css("border", "#FF0000 solid 1px")
$("#newpassword").focus();
return false;
}

Categories

Resources