I am using this plugin: jQuery Validate
I have a basic form like this:
HTML
<form class="cmxform" id="signupForm" method="get" action="">
<fieldset>
<legend>Validating a complete form</legend>
<label for="firstname">Firstname</label>
<input id="firstname" name="firstname" type="text" />
<label for="lastname">Lastname</label>
<input id="lastname" name="lastname" type="text" />
<label for="username">Username</label>
<input id="username" name="username" type="text" />
<label for="password">Password</label>
<input id="password" name="password" type="password" />
<label for="confirm_password">Confirm password</label>
<input id="confirm_password" name="confirm_password" type="password" />
<input class="submit" type="submit" value="Submit"/>
</fieldset>
</form>
jQuery
$().ready(function() {
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
}
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address"
}
});
});
I want to make the password need a capital letter and contain at least one number.
How would I change the rules just for password and add this in?
Here is a fiddle:
http://jsfiddle.net/dwhitmarsh/xXUWB/
You will have to add your own validation method first, before the validation occurs. Personally, I recommend the document's ready event.
You can use the following "scaffold":
$(function() {
$.validator.addMethod('capitalLetterMandatory', function(function(value, element) {
// Return true if the validation succeeded, false otherwise.
// Best achieved through an appropriate regular expression
});
});
Then, don't forget to actually hook that rule up to your field, in your rules definition block when initializing the validator:
rules: {
password: { // Note that in this line it's the field name, not the rule name, which can be confusing
capitalLetterMandatory: true, // rule name
mandatory: true
},
// Other rules go here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With