So I'm using jquery validate to validate a form, and it's working for the most part, but my confirm password input isn't doing anything. It doesn't show that it's a required field, when I'm telling it to be required just like the rest of the fields, and the equalTo: method I'm using doesn't work, however I don't think the equalTo: method is the problem because the required:true doesn't work either.
Here's my JQuery
<script type="text/javascript">
(function($,W,D)
{
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function()
{
//form validation rules
$("#user").validate({
wrapper: 'div',
errorLabelContainer: "#messageBox",
debug: false,
rules: {
username: {
required: true,
minlength: 5
},
password: {
required: true,
minlength: 5
},
confirmPassword: {
required: true,
equalTo: "#password"
},
termsOfService: "required",
},
messages: {
username: {
required: "Please enter a username",
minlength: "Must be at Least 5 characters",
},
password: {
required: "Please enter a password",
minlength: "Must be at least 5 characters"
},
confirmPassword:{
required: "Confirm Password required",
equalTo: "Passwords don't match"
},
termsOfService: "please accept our terms of service",
},
submitHandler: function(form) {
form.submit();
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
</script>
and here's my jsp page form
<form:form commandName="user" method="POST">
Username: <br><form:input path="username"/><br><br>
Password: <br><form:password path="password"/><br><br>
Confirm Password: <br><input type="password" id="confirmPassword"/><br><br>
Terms of Service<form:checkbox path="termsOfService" id="termsOfService" style="vertical-align: middle; margin-left: 15px;"/><br><br>
<input type ="submit" id="submitBtn" value="Submit"/><br><br>
</form:form>
As mentioned in comment, I'm not familiar with JSP but very much familiar with jQuery validation plugin,
First your are missing id="password" to password input
<form:password path="password" id="password" />
and then path to confirm password input
<form:password path="confirmPassword" id="confirmPassword"/>
jQuery validation plugin to set the rules based on inputs name attributes or in JSP path so not able to find confirm password because of missing path and equalTo failing because you binding it with "#password" but no id="password" given in password input
This question already has answers here:
jQuery Validate remote method usage to check if username already exists
(2 answers)
Closed 7 years ago.
I'm using jQuery Validator in order to process a simple form. Everything works as it should, but I would like to modify a little bit the validation process. I have integrated a small Ajax request to test whether the entered email already exists in the DB. The response is 1 in case the email already exists or 0 otherwise. I noticed that a label tag is created under the input field in case the email is not valid:
<label id="email-error" class="error" for="email">This field is required.</label>
Is it possible to override this generated label (after the jQuery Validator has validated that the provided email is valid), to indicate whether this email exists in the DB or not?
Suppose, for 1 the generated label will look like this:
<label id="email-error" class="error" for="email">This Email is already in use.</label>
This is the current configuration of the validator:
var $validator=$("#form-register").validate({
rules:{
email:{
required: true
}
}
});
This is the HTML form:
<form id="form-register" class="p-t-15" role="form">
<div class="form-group form-group-default" id="email_div">
<label>What's your email address?</label>
<div>
<input type="email" class="form-control" name="email" id="email" placeholder="Email">
</div>
</div>
</form>
You can use the remote option here:
$( "#form-register" ).validate({
rules: {
email: {
required: true,
email: true,
remote: "check-email.php"
}
}
});
Makes the email field required, an email and does a remote request to check if the given address is already taken. In addition, the http method is set to "post" and the username is sent alongside the email address.
$( "#form-register" ).validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
}
}
}
}
});
Guys I am using jQuery Validation plugin to validate the Input Text fields...
like this:
$("#formSettings").validate({
rules: {
sta: {
required: true,
},
crs: {
equalTo: "#password"
}
},
messages: {
email: {
required: "Please Provide Your Email Address",
email: "Provide Valid Email Address"
},
});
The issue: I need to match one textfield value with the other, each textfield have comma separated values and they should match before continuing, any idea how can I do that
like if textfield 1 is: 1,2,3,4,5,6 then textfield2 should match.
$('#selector').val().length
Above the basic jQuery version of .length After that you could do an if statement. Here is a brief untested test you try:
<input type="text" value="1,2,3,4,5" id="thing1">
<input type="text" value="1,2,3,4" id="thing2">
<input type="button" name="submit" value="submit" id="submit">
$('#submit').click(function(event){
var thing1 = $('#thing1').val().length;
var thing2 = $('#thing2').val().length;
if (thing1 == thing2) {
return true;
} else {
alert("Contents must have same length");
return false;
}
});
And the fiddle: http://jsfiddle.net/8XQB3/
Can anyone solve this fiddle. it has two fields password and confirm password. Validation needs to be done such that both password entered should be the same.
$(document).ready(function ()
{
$('#EditForm').validate({
rules: {
password: {
required: true
},
cpassword: {
required: true,
equalTo: "#password"
}
}
});
});
http://jsfiddle.net/kalai789/aCZgK/2/
Thanks in advance
Firstly the external version of jQuery you had loaded was very old (1.5.2) it appears incompatible with the current version of validate, I updated the fiddle to use 1.6.4 as that was the lowest available on jsFiddle. Secondly, the rules and other settings for the validate plugin are keyed on the name attribute of the element, not the id, so they need to be added:
<input type="password" name="password" id="password"/>
<input type="password" name="cpassword" value="" id="cpassword"/>
Working fiddle
use keyup method
http://jsfiddle.net/dbwMY/
check the info source
https://stackoverflow.com/a/9717796/1768043
Found similar question
Demo
jQuery('.validatedForm').validate({
rules : {
password : {
minlength : 5
},
password_confirm : {
minlength : 5,
equalTo : "#password"
}
}
});
I am using the jQuery validation plugin. Great stuff! I want to migrate my existing ASP.NET solution to use jQuery instead of the ASP.NET validators. I am missing a replacement for the regular expression validator. I want to be able to do something like this:
$("Textbox").rules("add", { regularExpression: "^[a-zA-Z'.\s]{1,40}$" })
How do I add a custom rule to achieve this?
Thanks to the answer of redsquare I added a method like this:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Please check your input."
);
Now all you need to do to validate against any regex is this:
$("#Textbox").rules("add", { regex: "^[a-zA-Z'.\\s]{1,40}$" })
Additionally, it looks like there is a file called additional-methods.js that contains the method "pattern", which can be a RegExp when created using the method without quotes.
Edit
The pattern function is now the preferred way to do this, making the example:
$("#Textbox").rules("add", { pattern: "^[a-zA-Z'.\\s]{1,40}$" })
https://cdnjs.com/libraries/jquery-validate
https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js
https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js
You can use the addMethod()
e.g
$.validator.addMethod('postalCode', function (value) {
return /^((\d{5}-\d{4})|(\d{5})|([A-Z]\d[A-Z]\s\d[A-Z]\d))$/.test(value);
}, 'Please enter a valid US or Canadian postal code.');
good article here https://web.archive.org/web/20130609222116/http://www.randallmorey.com/blog/2008/mar/16/extending-jquery-form-validation-plugin/
I had some trouble putting together all the pieces for doing a jQuery regular expression validator, but I got it to work... Here is a complete working example. It uses the 'Validation' plugin which can be found in jQuery Validation Plugin
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://YOURJQUERYPATH/js/jquery.js" type="text/javascript"></script>
<script src="http://YOURJQUERYPATH/js/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function() {
$.validator.addMethod("EMAIL", function(value, element) {
return this.optional(element) || /^[a-zA-Z0-9._-]+#[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);
}, "Email Address is invalid: Please enter a valid email address.");
$.validator.addMethod("PASSWORD",function(value,element){
return this.optional(element) || /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/i.test(value);
},"Passwords are 8-16 characters with uppercase letters, lowercase letters and at least one number.");
$.validator.addMethod("SUBMIT",function(value,element){
return this.optional(element) || /[^ ]/i.test(value);
},"You did not click the submit button.");
// Validate signup form on keyup and submit
$("#LOGIN").validate({
rules: {
EMAIL: "required EMAIL",
PASSWORD: "required PASSWORD",
SUBMIT: "required SUBMIT",
},
});
});
</script>
</head>
<body>
<div id="LOGIN_FORM" class="form">
<form id="LOGIN" name="LOGIN" method="post" action="/index/secure/authentication?action=login">
<h1>Log In</h1>
<div id="LOGIN_EMAIL">
<label for="EMAIL">Email Address</label>
<input id="EMAIL" name="EMAIL" type="text" value="" tabindex="1" />
</div>
<div id="LOGIN_PASSWORD">
<label for="PASSWORD">Password</label>
<input id="PASSWORD" name="PASSWORD" type="password" value="" tabindex="2" />
</div>
<div id="LOGIN_SUBMIT">
<input id="SUBMIT" name="SUBMIT" type="submit" value="Submit" tabindex="3" />
</div>
</form>
</div>
</body>
</html>
No reason to define the regex as a string.
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var check = false;
return this.optional(element) || regexp.test(value);
},
"Please check your input."
);
and
telephone: { required: true, regex : /^[\d\s]+$/, minlength: 5 },
tis better this way, no?
Extending PeterTheNiceGuy's answer a bit:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
if (regexp.constructor != RegExp)
regexp = new RegExp(regexp);
else if (regexp.global)
regexp.lastIndex = 0;
return this.optional(element) || regexp.test(value);
},
"Please check your input."
);
This would allow you to pass a regex object to the rule.
$("Textbox").rules("add", { regex: /^[a-zA-Z'.\s]{1,40}$/ });
Resetting the lastIndex property is necessary when the g-flag is set on the RegExp object. Otherwise it would start validating from the position of the last match with that regex, even if the subject string is different.
Some other ideas I had was be to enable you use arrays of regex's, and another rule for the negation of regex's:
$("password").rules("add", {
regex: [
/^[a-zA-Z'.\s]{8,40}$/,
/^.*[a-z].*$/,
/^.*[A-Z].*$/,
/^.*[0-9].*$/
],
'!regex': /password|123/
});
But implementing those would maybe be too much.
As mentioned on the addMethod documentation:
Please note: While the temptation is great to add a regex method that checks it's parameter against the value, it is much cleaner to encapsulate those regular expressions inside their own method. If you need lots of slightly different expressions, try to extract a common parameter. A library of regular expressions: http://regexlib.com/DisplayPatterns.aspx
So yes, you have to add a method for each regular expression. The overhead is minimal, while it allows you to give the regex a name (not to be underestimated), a default message (handy) and the ability to reuse it a various places, without duplicating the regex itself over and over.
I got it to work like this:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
return this.optional(element) || regexp.test(value);
},
"Please check your input."
);
$(function () {
$('#uiEmailAdress').focus();
$('#NewsletterForm').validate({
rules: {
uiEmailAdress:{
required: true,
email: true,
minlength: 5
},
uiConfirmEmailAdress:{
required: true,
email: true,
equalTo: '#uiEmailAdress'
},
DDLanguage:{
required: true
},
Testveld:{
required: true,
regex: /^[0-9]{3}$/
}
},
messages: {
uiEmailAdress:{
required: 'Verplicht veld',
email: 'Ongeldig emailadres',
minlength: 'Minimum 5 charaters vereist'
},
uiConfirmEmailAdress:{
required: 'Verplicht veld',
email: 'Ongeldig emailadres',
equalTo: 'Veld is niet gelijk aan E-mailadres'
},
DDLanguage:{
required: 'Verplicht veld'
},
Testveld:{
required: 'Verplicht veld',
regex: '_REGEX'
}
}
});
});
Make sure that the regex is between / :-)
You may use pattern defined in the additional-methods.js file. Note that this additional-methods.js file must be included after jQuery Validate dependency, then you can just use
$("#frm").validate({
rules: {
Textbox: {
pattern: /^[a-zA-Z'.\s]{1,40}$/
},
},
messages: {
Textbox: {
pattern: 'The Textbox string format is invalid'
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>
<form id="frm" method="get" action="">
<fieldset>
<p>
<label for="fullname">Textbox</label>
<input id="Textbox" name="Textbox" type="text">
</p>
</fieldset>
</form>
This is working code.
function validateSignup()
{
$.validator.addMethod(
"regex",
function(value, element, regexp)
{
if (regexp.constructor != RegExp)
regexp = new RegExp(regexp);
else if (regexp.global)
regexp.lastIndex = 0;
return this.optional(element) || regexp.test(value);
},
"Please check your input."
);
$('#signupForm').validate(
{
onkeyup : false,
errorClass: "req_mess",
ignore: ":hidden",
validClass: "signup_valid_class",
errorClass: "signup_error_class",
rules:
{
email:
{
required: true,
email: true,
regex: /^[A-Za-z0-9_]+\#[A-Za-z0-9_]+\.[A-Za-z0-9_]+/,
},
userId:
{
required: true,
minlength: 6,
maxlength: 15,
regex: /^[A-Za-z0-9_]{6,15}$/,
},
phoneNum:
{
required: true,
regex: /^[+-]{1}[0-9]{1,3}\-[0-9]{10}$/,
},
},
messages:
{
email:
{
required: 'You must enter a email',
regex: 'Please enter a valid email without spacial chars, ie, Example#gmail.com'
},
userId:
{
required: 'Alphanumeric, _, min:6, max:15',
regex: "Please enter any alphaNumeric char of length between 6-15, ie, sbp_arun_2016"
},
phoneNum:
{
required: "Please enter your phone number",
regex: "e.g. +91-1234567890"
},
},
submitHandler: function (form)
{
return true;
}
});
}
we mainly use the markup notation of jquery validation plugin and the posted samples did not work for us, when flags are present in the regex, e.g.
<input type="text" name="myfield" regex="/^[0-9]{3}$/i" />
therefore we use the following snippet
$.validator.addMethod(
"regex",
function(value, element, regstring) {
// fast exit on empty optional
if (this.optional(element)) {
return true;
}
var regParts = regstring.match(/^\/(.*?)\/([gim]*)$/);
if (regParts) {
// the parsed pattern had delimiters and modifiers. handle them.
var regexp = new RegExp(regParts[1], regParts[2]);
} else {
// we got pattern string without delimiters
var regexp = new RegExp(regstring);
}
return regexp.test(value);
},
"Please check your input."
);
Of course now one could combine this code, with one of the above to also allow passing RegExp objects into the plugin, but since we didn't needed it we left this exercise for the reader ;-).
PS: there is also bundled plugin for that, https://github.com/jzaefferer/jquery-validation/blob/master/src/additional/pattern.js
This worked for me, being one of the validation rules:
Zip: {
required: true,
regex: /^\d{5}(?:[-\s]\d{4})?$/
}
Hope it helps
$.validator.methods.checkEmail = function( value, element ) {
return this.optional( element ) || /[a-z]+#[a-z]+\.[a-z]+/.test( value );
}
$("#myForm").validate({
rules: {
email: {
required: true,
checkEmail: true
}
},
messages: {
email: "incorrect email"
}
});
Have you tried this??
$("Textbox").rules("add", { regex: "^[a-zA-Z'.\\s]{1,40}$", messages: { regex: "The text is invalid..." } })
Note: make sure to escape all the "\" of ur regex by adding another "\" in front of them else the regex wont work as expected.