How come my matching of the two email addresses still claims they don't match even though they are exactly the same? It's email2 that get's the error message.
* Email: <input type='text' name='email' /> <br/>
* Repeat email: <input type='text' name='email2' /> <br/>
$("#addagentform").live('blur',function(e){
$("#addagentform").validate({
rules: {
email: {
required: true,
email: true
},
email2: {
required: true,
equalTo: "#email"
},
}
});
});
I've found other with the same problem, but appearently with different problems than I'm having since their solution didn't help me.
Try wrapping that in a rules: {} block, like so:
* Email: <input type='text' id='email1' name='email1' /> <br/>
* Repeat email: <input type='text' id='email2' name='email2' /> <br/>
$("#addagentform").live('blur',function(e){
$("#addagentform").validate({
rules: {
email1: {
required: true,
email: true
},
email2: {
required: true,
email: true,
equalTo: '#email1'
}
}
});
});
Not sure if it really matters, but the convention is to use single quotes in rules, and field name email may not be valid, depending on which version of the plugin you're using. Try making the fields email1 and email2. And finally, you should provide an id as well for the fields in question.
You are not assigning id properties to your fields. #email may not find a target this way.
Try
<input type='text' name='email' id='email'/>
Related
I have been trying many times with JQuery for validating errors using customized messages, but I am still confused that where I am making the mistake.I have tried with the normal validating messages, but when I tried with the customized, it shows me an error.
Below is the sample code which i have tried so far and unsucessful in executing it.
<form id="myform">
<tr>
<td class="alpha">username</td>
<td>
<input type="username" type="text" value="">
</td>
</tr>
<br/>
<tr>
<td class="alpha">postcode</td>
<td>
<input type="postcode" type="text" value="">
</td>
</tr>
<input type="submit" />
</form>
$.validator.setDefaults({
submitHandler: function() {
alert("submitted!");
}
});
$document.ready(function() {
$("#myform").validate({
rules: {
password: "required",
postcode: {
required: true,
minlength: 3
}
},
messages: {
username: {
required: "*Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
postcode: {
required: "Field PostCode is required",
minlength: "Field PostCode must contain at least 3 characters"
}
}
});
});
As written, your code would not work with the default messages either.
Please read my comments in the code...
rules: {
password: "required", // <- input with name="password" (where is "password"?)
postcode: { // <- input with name="postcode"
required: true,
minlength: 3
}
},
messages: {
username: { // <- input with name="username"
required: "*Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
postcode: { // <- input with name="postcode"
required: "Field PostCode is required",
minlength: "Field PostCode must contain at least 3 characters"
}
}
The rules and messages objects' parameters are keyed by the name attribute of the input element. Your input elements do not contain any name attributes. The plugin mandates that all form inputs contain a unique name, and the plugin will not work without these.
You have invalid values for the type attribute. There are no such things as type="username" and type="postcode"; and you erroneously have more than one type attributes on each input, <input type="username" type="text" value="">
In your case, you don't even attempt to define any rules for a username field. You only have password and postcode within the rules object.
Fix your invalid HTML markup and JavaScript...
Remove all extraneous type attributes from each input.
Add a unique name attribute to each input.
Only reference your name attributes within rules and messages objects.
DEMO: jsfiddle.net/2tx6u7wf/
I'm using the jQuery Validation plugin:
I have several fields in a large form that I want to apply the same rules to. I've simplified the code for this example. This code doesn't work, but I want to do something like this. The second rule should apply to both first_name and last_name. I want to encapsulate all the rules here in this function and not edit the class lists of some of the form elements to add a required class or whatever.
(Again, I have several different groups of form fields with different requirements that I want to group. I only put required: true in that element for simplicity)
$('#affiliate_signup').validate(
{
rules:
{
email: {
required: true,
email: true
},
first_name,last_name: {
required: true
},
password: {
required: true,
minlength: 4
}
}
});
Thanks in advance.
For the purposes of my example, this is the base starting code:
HTML:
<input type="text" name="field_1" />
<input type="text" name="field_2" />
<input type="text" name="field_3" />
jQuery:
$('#myForm').validate({
rules: {
field_1: {
required: true,
number: true
},
field_2: {
required: true,
number: true
},
field_3: {
required: true,
number: true
}
}
});
http://jsfiddle.net/9W3F7
Option 1a) You can pull out the groups of rules and combine them into common variables.
var ruleSet1 = {
required: true,
number: true
};
$('#myForm').validate({
rules: {
field_1: ruleSet1,
field_2: ruleSet1,
field_3: ruleSet1
}
});
http://jsfiddle.net/9W3F7/1
Option 1b) Related to 1a above but depending on your level of complexity, can separate out the rules that are common to certain groups and use .extend() to recombine them in an infinite numbers of ways.
var ruleSet_default = {
required: true,
number: true
};
var ruleSet1 = {
max: 99
};
$.extend(ruleSet1, ruleSet_default); // combines defaults into set 1
var ruleSet2 = {
min: 3
};
$.extend(ruleSet2, ruleSet_default); // combines defaults into set 2
$('#myForm').validate({
rules: {
field_1: ruleSet2,
field_2: ruleSet_default,
field_3: ruleSet1
}
});
End Result:
field_1 will be a required number no less than 3.
field_2 will just be a required number.
field_3 will be a required number no greater than 99.
http://jsfiddle.net/9W3F7/2
Option 2a) You can assign classes to your fields based on desired common rules and then assign those rules to the classes. Using the addClassRules method we're taking compound rules and turning them into a class name.
HTML:
<input type="text" name="field_1" class="num" />
<input type="text" name="field_2" class="num" />
<input type="text" name="field_3" class="num" />
jQuery:
$('#myform').validate({ // initialize the plugin
// other options
});
$.validator.addClassRules({
num: {
required: true,
number: true
}
});
http://jsfiddle.net/9W3F7/4/
Option 2b) The main difference from option 2a is that you can use this to assign rules to dynamically created input elements by calling rules('add') method immediately after you create them. You could use class as the selector, but it's not required. As you can see below, we've used a wildcard selector instead of class.
The .rules() method must be called any time after invoking .validate().
jQuery:
$('#myForm').validate({
// your other plugin options
});
$('[name*="field"]').each(function() {
$(this).rules('add', {
required: true,
number: true
});
});
http://jsfiddle.net/9W3F7/5/
Documentation:
rules('add') method
addClassRules method
You can use the 'getter' syntax in this way:
{
rules:
{
email: {
required: true,
email: true
},
first_name: {
required: true
},
get last_name() {return this.first_name},
password: {
required: true,
minlength: 4
}
}
}
If I understood you right, you want to apply many rules to many fields, that may differ at some rules, but you are too lazy to repeat yourself with the same rules to other fields.
However, with jQuery validate it's possible to have more than one rule on one input field. Just use the array notation here.
To achieve your use case, just add data attributes to each input field with the rules you want to apply to it. In best case, use an url encoded json format, so that you just need one data attribute per each input field. E. g.:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>validate test</title>
</head>
<body>
<form id="myForm" name="myForm" method="post" action="www.example.com/my-url">
<input type="text" name="txt1" data-rules="%7B%22required%22%3Atrue%2C%22minlength%22%3A2%2C%22maxlength%22%3A10%7D" />
<input type="text" name="txt2" data-rules="%7B%22required%22%3Atrue%2C%22minlength%22%3A2%2C%22maxlength%22%3A10%7D" />
<input type="number" name="number1" data-rules="%7B%22required%22%3Atrue%2C%22number%22%3Atrue%2C%22min%22%3A1%2C%22max%22%3A999%7D" />
<input type="email" name="email1" data-rules="%7B%22required%22%3Atrue%2C%22email%22%3Atrue%2C%22minlength%22%3A20%7D" />
<input type="email" name="email2" data-rules="%7B%22required%22%3Atrue%2C%22email%22%3Atrue%2C%22minlength%22%3A20%7D" />
</form>
<script type="text/javascript">
var $field = null;
var rules = {};
$('#myForm input, #myForm textarea').each(function (index, field) {
$field = $(field);
rules[$field.attr('name')] = JSON.parse(decodeURIComponent($field.attr('data-rules')));
});
$('#myForm').validate(rules);
</script>
</body>
</html>
The basic technology behind that is simple:
Create your fields with the `data-`` attribute.
Loop over each input field to grab the rules that you want to apply on it.
Apply your collected rules to the form element
You could also use input groups with the same validators that way, e. g. by using classes for it and predefined JavaScript variables with the rules object. I think you got the idea on how to get lazy in an elegant way ;-)
I'm trying to override the default message in jquery validation message I did as the documentation told but no use it is still show "This field is required." ?
http://jsfiddle.net/7Yrz7/
$(function () {
$('form').validate({
rules: {
email:"required",
password:"required",
messages: {
email: "Please enter an email address.",
password: "This field is required."
}
}
});
});
It should be:
$("form").validate({
rules: {
email: "required",
password: "required"
}, // <-- here
messages: {
email: "Please enter an email address.",
password: "This field is required."
}
});
You need to close the rules before using messages here.
Updated Fiddle
For using Validate plugin you have to add Rule first and then message.
The Scripts
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}, // end of rules
messages: {
field1: "You cannot leave field1 blank",
field2: "You cannot leave field1 blank"
}// end of message
});
});
The HTML
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
Options: http://jqueryvalidation.org/validate
Methods: http://jqueryvalidation.org/category/plugin/
Standard Rules: http://jqueryvalidation.org/category/methods/
Optional Rules available with the additional-methods.js file:
maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension
I am trying to use jQuery to validate my two password fields with each other.
My code looks like this:
jQuery('#settingsForm').validate(
rules : {
npassword : {
},
pass_check : {
equalTo : '#npassword'
}
}
});
This is the HTML for the input fields:
<label for='npassword'>New Password</label>
<input type='password' class='span10 password_check' name='npassword' id='npassword' value='' placeholder='New Password'>
<div class='separator'></div>
<label for='pass_check'>Confirm New Password</label>
<input type='password' class='span10' name='pass_check' id='pass_check' value='' placeholder='Confirm New Password'>
<div class='separator'></div>
Although this doesn't do anything. What should I change? I am new to jQuery and Javascript in general.
Thanks in advance.
You should fill out the configuration for npassword, e.g. by using required: true. See here: http://jsfiddle.net/JtTgM/
1) You are missing an opening brace, {, right after .validate(:
jQuery('#settingsForm').validate({ // <-- opening brace { was missing
2) Maybe you want to specify the required rule for the first password field. Otherwise, when both fields are blank, they both match and the form is valid.
npassword: {
required: true
},
3) You can override the default messages with the messages option:
jQuery('#settingsForm').validate({
rules: {
npassword: {
required: true
},
pass_check: {
equalTo: '#npassword'
}
},
messages: {
npassword: {
required: "this field is required"
},
pass_check: {
equalTo: "the passwords must match"
}
}
});
Working DEMO: http://jsfiddle.net/vsLWg/
$( "#Form").validate({
rules: {
old_password: "required",
password: "required",
new_password: {
equalTo: "#password"
}
}
});
I have a simple login form and have jQuery validate replacing the field labels when there's an error to display. The problem is that, once the error is cleared, the label disappears. I would like to find a way to revert back to the previous label's content, or rebuild that label when the field is valid...
Here's my code:
$(document).ready(function(){
$("#login").validate({
errorPlacement: function(error, element) {
element.prev().replaceWith(error);
},
rules: {
"email": {
required: true,
email:true,
},
"password": {
required: true,
minlength: 6
}
},
messages: {
email: {
required: "Please enter your email address.",
email: "Please enter a <u>valid</u> email address"
},
password: {
required: "Please enter your password.",
minlength: "Please enter a password with 6 characters or more."
}
},
});
});
And the HTML:
<form name="login" id="login" method="post" action="authenticate.php">
<p>
<label for="email">Email Address:</label>
<input type="text" name="email" id="email" class="required email" />
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" class="required" />
</p>
<p>
<input type="submit" value="Log In" id="submit" />
</p>
In essence, when the user submits the form, if there's no data in the Email field, then the label for email gets replaced with the error. But once it has valid input, I want to put back the original label.
Thanks in advance for any suggestions,
Z
I actually worked out a compromise whereby, instead of replacing the previous label with the error label, I'm appending a span into that label using error.appendTo(element.prev()) and errorElement: "span". Here's the new code:
$(document).ready(function(){
$("#login").validate({
errorElement: "span",
errorPlacement: function(error, element) {
error.appendTo(element.prev());
//element.prev().replaceWith(error);
},
rules: {
"email": {
required: true,
email:true,
},
"password": {
required: true,
minlength: 6
}
},
messages: {
email: {
required: " is Required",
email: " is Improperly Formatted"
},
password: {
required: " is Required",
minlength: " is not Long Enough"
}
},
});
});
It's less than ideal, but at least when the span appears, the error code is where I want it to be, and when it disappears, the label remains intact. I just made it so the label and the error complete each other like sentences... Eg, "Email Address" " is required." or "Email Address" " is not properly formatted."
Thanks to everybody that contributed here,
Z
You can remove
errorPlacement: function(error, element) {
element.prev().replaceWith(error);
},
and the messages should appear beside the textboxes instead.
You can try to removeChild(label),and attach a new one to it when the error accur. Toggling the label seems to make sence