how to use regex code in jquery validator rules - javascript

Iam not understanding to do validation for the 'FullName' field..
Below are the validations required for the 'FullName' field:
only letters a to z (lower case), "-" (dash or hyphen) and " "
(space) are allowed,
the "-" (dash) AND " " (space) letters MUST be entered,
the "-" or the " " letter must not be either the first or the last
letter entered,
"-" must not be the immediate neighbour or adjacent (before or after)
to a " ",
"-" or " " must not be the immediate neighbour (adjacent) to itself.
I knew I can do in this way:
$('#fullName').blur(function(){
var input = $('#fullName').val();
if( !/[^a-z0-9 -]/.test(input) &&
/ /.test(input) && /-/.test(input) &&
!/^[ |-]|[ |-]$/.test(input) &&
!/ -|- |--| /.test(input))
{
$('.error').remove();
}
else{
$('#fullName')
.after('<span class="error">Your Name should be entered like: "blahblah" </span>');
}
});
BUT I am not understanding how to insert above regex code into here:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script type="text/javascript" src="http://jquery-joshbush.googlecode.com/files/jquery.maskedinput-1.2.1.pack.js"></script>
<script>
$(document).ready(function(){
$("#fullname").focus();
$("#fullname").addMethod("alphanumeric", function(value, element) {
return ! $("#fullname").methods.required(value, element) || /^[a-zA-Z0-9_]+$/i.test(value);
} , "Letters, numbers or underscores only please");
$("#ourform").validate({
onfocusout: function(element) { $(element).valid(); } ,
rules: {
fullname : {
required: true,
maxlength: 14,
alphanumeric : false
},
email: {
required: true,
email: true
}
},
messages: {
fullname : {
required: "Please specify your Full Name",
maxlength: "Please enter only upto 14 characters",
alphanumeric : "do not enter alphanumeric"
},
email: {
required: "We need your email address to contact you",
email: "Your email address must be in the format of name#domain.com"
}
}
});
});
</script>
<style>
.error {color: red;}
</style>
</head>
<body>
<form id="ourform" method="get" action="">
<fieldset>
<p>
<label for="fullname">Full Name</label>
<em>*</em><input id="fullname" name="fullname" size="25" class="required" maxlength="14" />
</p>
<p>
<label for="email">Email</label>
<em>*</em><input id="email" name="email" size="25" class="required email" />
</p>
</fieldset>
</form>
</body>
</html>
EDITED:
- FullName (both first and family name - use ONE field for both),

You have two questions here:
How to validate the full name per your rules.
How to add custom jQuery validator validation rules.
How to add custom jQuery validator validation rules
Here is an example of validating the field has the value "Mark" for fullname:
$(document).ready(function() {
var fullname_invalid = function(value) {
return value === "Mark";
}
$.validator.addMethod("custom_fullname", function(value, element) {
return fullname_invalid(value);
}, 'Your Name should be entered like: "Mark"');
$('#signup').validate({
rules: {
fullname: {
required: true,
custom_fullname: true
}
}
});
$('#signup').on('submit', function(event) {
event.preventDefault();
});
});​
HTML:
<form id="signup" action="/action">
<input name="fullname" type="text" />
<input type="submit">
</form>​
Demo: jsfiddle
Reference: jQuery Validate Plugin - How to create a simple, custom rule?
How to validate the full name per your rules
$(document).ready(function() {
var validCharactersRegex = new RegExp(/^[a-zA-Z0-9 -]+$/);
var doesNotStartWithDashOrSpace = new RegExp(/^[^ -]/);
var fullname_invalid = function(value) {
return validCharactersRegex.test(value) && doesNotStartWithDashOrSpace.test(value) && value.indexOf(' ') == -1 && value.indexOf('--') == -1 && value.indexOf(' -') == -1 && value.indexOf('- ') == -1;
}
$.validator.addMethod("custom_fullname", function(value, element) {
return fullname_invalid(value);
}, 'Your Name should be entered like: "blahblah"');
$('#signup').validate({
rules: {
fullname: {
required: true,
custom_fullname: true
}
}
});
$('#signup').on('submit', function(event) {
event.preventDefault();
});
});​
Demo: jsfiddle

Related

Form element validation using jQuery

I am trying to make a validation page and I need to stop saying "Please fill in the form" when text is entered in the text box. I only needed to validate when the text boxes are empty
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:kyletab03#gmail.com" name="myForm" method="post" onsubmit="return validation();" enctype="text/plain">
Name:
<input type="text" name="name" id="name" /><br />
Surname:
<input type="text" name="surname" id="surname" /><br />
Email:
<input type="email" name="email" id="email" /><br />
Message:
<textarea name="Message" maxlength="3500"></textarea><br />
<button id="submit" onclick="validation()">Submit</button>
</form>
<script>
var name = $("#name").value;
var surname = $("#surname").value;
var email = $("#email").value;
var comments = $("#comments").value;
function validation() {
if (name == "" || surname == "" || email == "" || comments == "") {
document.myForm.name.setCustomValidity("Please fill out this field");
document.myForm.surname.setCustomValidity("Please fill out this field");
document.myForm.email.setCustomValidity("Please fill out this field");
document.myForm.comments.setCustomValidity("Please fill out this field");
} else {
document.myForm.name.setCustomValidity();
document.myForm.surname.setCustomValidity();
document.myForm.email.setCustomValidity();
document.myForm.comments.setCustomValidity();
}
}
</script>
your code is showing an error because in your last line you are using "comments" instead of "Message", also setCustomValidity() takes a string with the error message or an empty string and for it to work well consider using the document's methods for retrieving elements, in addition you will need to add reportValidity() so your code should look like this
if (name == "" || surname == "" || email == "" || comments == "") {
name=document.getElementById('name')
name.setCustomValidity("Please fill out this field");
name.reportValidity()
}
else
name.setCustomValidity('');
name.reportValidity()
also you can consider using a helper function to use the element id dynamically
Update:
you can use this it will work
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:kyletab03#gmail.com" name="myForm" method="post" id='myform' enctype="text/plain">
Name:
<input type="text" name="name" id="name" required="required"/><br />
Surname:
<input type="text" name="surname" id="surname" required="required" /><br />
Email:
<input type="email" name="email" id="email" required="required" /><br />
Message:
<textarea name="Message" id="message" maxlength="3500" required="required"></textarea><br />
<button onlclick='validation()'>Submit</button>
</form>
<script>
function validate(inputID)
{
var input = document.getElementById(inputID);
var validityState_object = input.validity;
if (validityState_object.valueMissing)
{
input.setCustomValidity('Please fill out this field');
input.reportValidity();
}
else
{
input.setCustomValidity('');
input.reportValidity();
}
}
function validation() {
var name= document.getElementById('name').value
var surname=document.getElementById('surname').value
var email=document.getElementById('email').value
var message=document.getElementById('message').value
validate('name')
validate('surname')
validate('email')
validate('message')
if (name!=''&&surname!=''&&email!=''&&message!='') {
$('#myform').submit();
}
}
</script>
The easiest way to validate forms with jquery is to use jquery validate.
I would definately advise you NOT to use mailto directly in your form post url simply because spam bots and things like that may catch hold of your form and try to use it to send spam mail. i add jquery validation and captcha on all of the contact us pages that i create for clients.
$('#frmsendemail').validate({ // Send Email Form
ignore: '.ignore',
rules: {
seFullname: {
required: true,
minlength: 2
},
seContact: {
required: true,
phonesUK: true,
},
seMail: {
required: true,
email: true
},
seMsg: {
required: true
},
seCaptchaStatus: {
required: function () {
// verify the user response
var thisresponse = grecaptcha.getResponse(seCaptcha);
if (thisresponse == "") {
return true;
} else {
return false;
}
}
}
},
messages: {
seFullname: {
required: "Please Enter Your Name",
minlength: jQuery.validator.format("Please ensure you enter a name more than {0} characters long.")
},
seContact: {
required: "Please Enter a contact number",
phonesUK: "Your Contact Numer should be in the format of: 07123 456 789 or 0123 123 4567",
minlength: jQuery.validator.format("Your contact number should me at least {0} numbers.")
},
seMail: {
required: "Please Enter Your Email Address",
email: "Your email address should be in the format of "username#domain.com""
},
seMsg: "Please Enter A Message",
seCaptchaStatus: "Please complete reCaptcha."
},
highlight: function (element) {
var id_attr = "#" + $(element).attr("id");
$(element).closest('.pure-form-control-group').removeClass('border-success icon-valid').addClass('border-error icon-invalid');
$(id_attr).removeClass('glyphicon-ok icon-valid').addClass('glyphicon-remove icon-invalid');
},
unhighlight: function (element) {
var id_attr = "#" + $(element).attr("id");
$(element).closest('.pure-form-control-group').removeClass('border-danger icon-valid').addClass('border-success icon-valid');
$(id_attr).removeClass('glyphicon-remove icon-invalid').addClass('glyphicon-ok icon-valid');
},
showErrors: function (errorMap, errorList) {
$(".seerrors").html('<h6><i class="fa fa-exclamation-circle"></i> Your form contains ' +
this.numberOfInvalids() +
' errors, see details below.</h6');
this.defaultShowErrors();
},
validClass: "border-success",
invalidClass: "border-danger",
errorClass: "border-danger",
errorElement: 'div',
errorLabelContainer: ".seerrors",
submitHandler: function () {
//Now that all validation is satified we can send the form to the mail script.
//Using AJAX we can send the form, get email sent and get a response and display a nice
//message to the user saying thank you.
//For Debugging
//console.log("Sending Form");
$.post("../php/sendemail.php", $('#frmsendemail').serialize(), function (result) {
//do stuff with returned data here
//result = $.parseJSON(result);
console.log(result.Status);
if (result.Status == "Error") {
//Create message from returned data.
//This helps the user see what went wrong.
//If its a form error they can correct it,
//if not then they can see whats wrong and alert us.
var message3 = '<p style="font-size:10pt;text-align:left !important;">We encountered an error while processing the information you requested to send.</p><p style="font-size:10px;text-align:left;">We appologise for this, details of the error are included below.<p><hr><p style="text-align:left;font-size:10px;">Error Details:' + result.Reason.toString() + '</p><pstyle="text-align:left;font-size:10px;">If this error persists, please email enquiries#cadsolutions.wales</p>';
// Show JConfirm Dialog with error.
$.confirm({
title: '<h2 style="text-align:left"><i class="fa fa-exclamation-circle"></i> We encountered an error<h2>',
content: message3,
type: 'red',
// Set Theme for the popup
theme: 'Material',
typeAnimated: true,
buttons: {
close: function () {}
}
});
The above code is from a page that i created for a contact us script. the script sets all the inputs that are on the page using the name= attribute and then sets messages for the inputs when validation rules are not met, highlights and un-highlights the fields with errors, shows error messages in a set div tag and then handles form submit when the form is valid. :)

Multiple Input Validation with regex

I have a webform in which a user has to fill in details. I am using Javascript and html in order to do multiple input validation with regular expressions. I have part of the javascript + html code below. The variables a-g are regexes of each input field required.
I created an empty Array called Err_arr to stored the errors that has met the conditions (e.g. if the user does not input anything / if the user does not fulfil the required format of input) The error message will be pushed into the array. The last if statement will be used to check whether the array is not empty, hence it will print out all the error messages on multiple lines depending on what the conditions are.
function validateForm() {
var cname = document.getElementById("cname").value;
var odate = document.getElementById("odate").value;
var cno = document.getElementById("cno").value;
var ccn = document.getElementById("ccn").value;
var expm = document.getElementById("expm").value;
var expy = document.getElementById("expy").value;
var cvv = document.getElementById("cvv").value;
var Err_Arr = [];
var a = /^(\w\w+)\s(\w+)$/;
var b = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
var c = /[0-9]{8}/;
var d = /[0-9]{16}/;
var e = /0[0-1]1[0-9]){2}/;
var f = /[0-9]{4}/;
var g = /[0-9]{3}/;
if (cname == null || cname == "") {
Err_Arr.push("Please Enter Info - Customer Name");
}
if (odate == null || odate == "") {
Err_Arr.push("Please Enter Info - Order Date");
}
if (cno == null || cno == "") {
Err_Arr.push("Please Enter Info - Contact No");
}
if (ccn == null || ccn == "") {
Err_Arr.push("Please Enter Info - Credit Card Number");
}
if (expm == null || expm == "") {
Err_Arr.push("Please Enter Info - Expiry Month");
}
if (expy == null || expy == "") {
Err_Arr.push("Please Enter Info - Expiry Year");
}
if (cvv == null || cvv == "") {
Err_Arr.push("Please Enter Info - CVV No");
}
if (cname.test(a) == false) {
Err_Arr.push("Enter correct input");
}
if (odate.test(b) == false) {
Err_Arr.push("Enter correct input");
}
if (cno.test(c) == false) {
Err_Arr.push("Enter correct input");
}
if (ccn.test(d) == false) {
Err_Arr.push("Enter correct input");
}
if (expm.test(e) == false) {
Err_Arr.push("Enter correct input");
}
if (expy.test(f) == false) {
Err_Arr.push("Enter correct input");
}
if (cvv.test(g) == false) {
Err_Arr.push("Enter correct input");
}
if (Err_Arr.length > 0) {
alert(Err_Arr.join("\n"));
}
}
<h2>Part 3 - Javascript with Alert Box</h2>
<form method="get" onsubmit="return validateForm()" name="form1">
Customer name: <input id="cname" type="text" name="cname" autocomplete="off"> <br \> Order date: <input id="odate" type="text" name="odate" autocomplete="off"> <br \> Contact number: (e.g. 98765432) <input id="cno" type="text" name="cno" autocomplete="off"> <br \> Credit card number: (e.g. 123456789) <input id="ccn" type="text" name="ccn" autocomplete="off"> <br \> Expiry date - month part (mm): <input id="expm" type="text" name="expm" autocomplete="off"> <br \> Expiry date - year part (yyyy): <input id="expy"
type="text" name="expy" autocomplete="off"> <br \> CVV Number (e.g. 123): <input id="cvv" type="text" name="cvv" autocomplete="off"> <br \>
<input type="submit" value="Submit">
</form>
I expect the whole web form to give me a whole list of alerts in the conditions that I did not satisfy for the if statements. Instead, my code is not running at all.
The intent of your code is correct. Reason why alerts doesn't show:
A syntax error in var e. notice the missing pair of the parenthesis. should be /0[0-1]1([0-9]){2}/;
.test() is used incorrectly. please refer to w3schools tutorial how to use test. Basically, test() is a method in the Regexp object in javascript. So it should be like regexObject.test(yourString)
Fixing all that most likely will make your code run without issues.
function validateForm() {
var cname = document.getElementById("cname").value;
var Err_Arr = [];
var a = new RegExp(/^(\w\w+)\s(\w+)$/);
if (cname == null || cname == "") {
Err_Arr.push("Please Enter Info - Customer Name");
}
if (!a.test(cname)) {
Err_Arr.push("Enter correct input");
}
if (Err_Arr.length > 0) {
alert(Err_Arr.join("\n"));
}
}
<h2>Part 3 - Javascript with Alert Box</h2>
<form method="get" onsubmit="return validateForm()" name="form1">
Customer name:<input id="cname" type="text" name="cname" autocomplete="off"> <br \>
<input type="submit" value="Submit">
</form>
You have some mistakes:
an invalid regex for e as it has unbalanced parentheses
Strings don't have a test method; regexes do
The suggestion for the credit card number in your HTML would not pass the corresponding regex (that requires 16 digits)
There are also some shorter ways to do things:
if (cname == null || cname == "")
can be just:
if (!cname)
More importantly, you have a lot of code repetition. You could avoid that by doing things in a loop:
function validateForm() {
var validations = [
{ input: "cname", regex: /^(\w\w+)\s(\w+)$/, name: "Customer name" },
{ input: "odate", regex: /^(0?[1-9]|[12]\d|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/, name: "Order date" },
{ input: "cno", regex: /^\d{8}$/, name: "Contact No" },
{ input: "ccn", regex: /^\d{16}$/, name: "Credit Card Number" },
{ input: "expm", regex: /^0?[1-9]|1[012]$/, name: "Expiry Month" }, // Correct regex
{ input: "expy", regex: /^\d{4}$/, name: "Expiry Year" },
{ input: "cvv", regex: /^\d{3}$/, name: "CVV No" }
];
var errors = validations.map(({input, regex, name}) => {
var value = document.getElementById(input).value;
if (!value) return "Please Enter Info - " + name;
if (!regex.test(value)) return "Enter correct input - " + name;
}).filter(Boolean);
if (errors.length) {
alert(errors.join("\n"));
return false;
}
return true;
}
<h2>Part 3 - Javascript with Alert Box</h2>
<form method="get" onsubmit="return validateForm()" name="form1">
Customer name: <input id="cname" type="text" name="cname" autocomplete="off"> <br \>
Order date: <input id="odate" type="text" name="odate" autocomplete="off"> <br \>
Contact number: (e.g. 98765432) <input id="cno" type="text" name="cno" autocomplete="off"> <br \>
Credit card number: (e.g. 1234567890123456) <input id="ccn" type="text" name="ccn" autocomplete="off"> <br \>
Expiry date - month part (mm): <input id="expm" type="text" name="expm" autocomplete="off"> <br \>
Expiry date - year part (yyyy): <input id="expy" type="text" name="expy" autocomplete="off"> <br \>
CVV Number (e.g. 123): <input id="cvv" type="text" name="cvv" autocomplete="off"> <br \>
<input type="submit" value="Submit">
</form>

jquery validate rules with multiple if/else condition

I want to use jquery validate() rule to 2 cross fields. If either of the field is typed in the other one is also required. Also, once they are required there format for number field should be 1st 15 digits should be integer and date field should be mm/dd/yyyy format and date should be less than todays date.
//..
$("#adjustmentsFormID").validate({
rules: {
refTranNbr: "required",
refTranDate: "required"
},
messages: {
refTranNbr: {
required: function (element) {
if($("#refTranDate").val().length > 0){
return "Please enter the reference transaction number ";
} else if(!refNumChk($("#refTranNbr").val())){
return "Please enter a valid Reference Transaction Number";
} else {
return false;
}
}
},
refTranDate: {
required : function (element) {
var tdate = $("#refTranDate").val();
if($("#refTranNbr").val().length > 0){
return "Please enter a date for the Refering Transaction to complete this transaction.";
}else if((new Date() > new Date(tdate))) {
return "Please enter a reference transaction date less than today's date.";
}else{
return false;
}
}
},
});
..//
In both the cases the 1st condition for required field works. However for refNum field the 2nd condition which has refNumChk isnot working. Actually its not getting called. Similarly for refTranDate required field validation works however date > tDate is not getting checked. Not sure if this method would work or should i do something different for multiple conditions.
Your approach to jQuery validation is wrong, the messages is used to return only the error message in case of an validation error.
So the only validation you are doing is the required validation, you can add custom validation rules to solve this
jQuery(function($) {
jQuery.validator.addMethod("refNumChk", function(value, element, params) {
return this.optional(element) || /^\d{15}[A-Z]$/.test(value);
}, jQuery.validator.format("Enter a value in forat aa-999"));
jQuery.validator.addMethod("lessThanToday", function(value, element, params) {
return this.optional(element) || new Date() > new Date(value);
}, jQuery.validator.format("Value should be less than today"));
$("#adjustmentsFormID").validate({
rules: {
refTranNbr: {
required: true,
//refNumChk: true
pattern: /^\d{15}[A-Z]$/
},
refTranDate: {
required: true,
lessThanToday: true
}
},
messages: {
refTranNbr: {
required: "Please enter the reference transaction number",
pattern: "Please enter a valid Reference Transaction Number"
},
refTranDate: {
required: "Please enter a date for the Refering Transaction to complete this transaction.",
lessThanToday: "Please enter a reference transaction date less than today's date."
},
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>
<form id="adjustmentsFormID" method="post" action="">
<div>
<input name="refTranNbr" />
</div>
<div>
<input name="refTranDate" />
</div>
<input type="submit" value="Save" />
</form>

Validation isn't working and now my site is broke as well

I had the basics "insert numbers, output answer" aspect of this working fine. But i need to put validation into the site so only certain things work. My site upon putting validation in, stopped working altogether, and i dont fully understand why or whats going on.
JS fiddle : http://jsfiddle.net/ufs869wu/
HTML:
<form id="form1" name="form1" method="post" action="">
<label for="txtAge">Age:</label>
<input type="text" class="txtInput" id="txtAge" value="0"/><p id="ageRes"></p>
<br/>
<label for="txtMass">Mass in Lbs:</label>
<input type="text" class="txtInput" id="txtMass" value="0"/>
<br/>
<label for="txtHinch">Height in Inches:</label>
<input type="text" class="txtInput" id="txtHinch" value="0"/>
<br/>
<input type="button" id="btnCalc" value="Calculate"/>
<p id="result2">Result</p>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="BMI.js"></script>
</body>
and JS
// JavaScript Document
$(function () {
//Identify Variables
var txtMass, txtHinch, result;
var isValid = $('#form1').validate().form();
// attach event listener to the toggle button's click event
$('#btnCalc').click(function () {
//Set validator
$.validator.setDefaults({
errorElement: "span",
errorClass: "form_error",
errorPlacement: function(error,element){
error.insertAfter(element)
}
});
$.extend($.validator.messages,{
required: "* Required field"
});
//Set Validation perameters
$("#form1").validate({
rules: {
txtAge: {
required: true,
range: [1, 120],
digits: true
},
txtMass: {
require: true,
digits: true
},
txtHinch: {
requre: true,
digits: true
}
}
});
if (isValid) {
//Set Age range for form accuracy
if (txtAge < 16 || txtAage > 80){
//Output
$('#ageRes').html('Results may not be accurate at your age')
} else { (txtAge >= 16 || txtAge <= 80)
$('#ageRes').html('Results should be accurate considering your age')
//Equation for BMI
result = ($('#txtMass').val() / ($('#txtHinch').val() * $('#txtHinch').val())) * 703;}
//If - Else statement from output of BMI equation
if (result < 16){
$('#result2').html('Result: '+result.toFixed(1) + ' you are Severely underweight')
} else if (result <=18 ){
$('#result2').html('Result: '+result.toFixed(1) + ' you are underweight')
} else if (result <=24){
$('#result2').html('Result: '+result.toFixed(1) + ' you are healthy')
} else if (result <= 30 ){
$('#result2').html('Result: '+result.toFixed(1) + ' you are seriously overweight')
} else if (result <=35 ){
$('#result2').html('Result: '+result.toFixed(1) + ' you are obese')
} else if (result <=40 ){
$('#result2').html('Result: '+result.toFixed(1) + ' you are seriously obese')
}
}
});
});
Thanks for any and all help!
You are calling '$' before jquery has been loaded, and are getting a '$' is undefined error.
Try moving this line up into the head section of your html.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
Also, are you including the jquery validation plugin somewhere?. I don't see it being included anywhere.

Using jquery validate with multiple fields of the same name

I am trying to get jquery validate to work on multiple fields. Reason being I have dynamically generated fields added and they are simply a list of phone numbers from none to as many as required. A button adds another number.
So I thought I'd put together a basic example and followed the concept from the accepted answer in the following link:
Using JQuery Validate Plugin to validate multiple form fields with identical names
However, it's not doing anything useful. Why is it not working?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.delegate.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script>
$("#submit").click(function(){
$("field").each(function(){
$(this).rules("add", {
required: true,
email: true,
messages: {
required: "Specify a valid email"
}
});
})
});
$(document).ready(function(){
$("#myform").validate();
});
</script>
</head>
<body>
<form id="myform">
<label for="field">Required, email: </label>
<input class="left" id="field" name="field" />
<input class="left" id="field" name="field" />
<input class="left" id="field" name="field" />
<input class="left" id="field" name="field" />
<br/>
<input type="submit" value="Validate!" id="submit" name="submit" />
</form>
</body>
</html>
This: $("field").each(function(){
Should be: $("[name=field]").each(function(){
Also your IDs should be unique, you'll get unpredictable behavior when this isn't true. Also, you should move the rule adding inside the document.ready, like this (this is now all your script):
$(function(){
$("#myform").validate();
$("[name=field]").each(function(){
$(this).rules("add", {
required: true,
email: true,
messages: {
required: "Specify a valid email"
}
});
});
});
#pratik
JqueryValidation maintaining rulesCache, You need to modify core library.
elements: function() {
var validator = this,
rulesCache = {};
// select all valid inputs inside the form (no submit or reset buttons)
return $(this.currentForm)
.find("input, select, textarea")
.not(":submit, :reset, :image, [disabled]")
.not(this.settings.ignore)
.filter(function() {
if (!this.name && validator.settings.debug && window.console) {
console.error("%o has no name assigned", this);
}
// select only the first element for each name, and only those with rules specified
if (this.name in rulesCache || !validator.objectLength($(this).rules())) {
return false;
}
rulesCache[this.name] = true;
return true;
});
},
Just comment the rulesCache[this.name] = true;
elements: function() {
var validator = this,
rulesCache = {};
// select all valid inputs inside the form (no submit or reset buttons)
return $(this.currentForm)
.find("input, select, textarea")
.not(":submit, :reset, :image, [disabled]")
.not(this.settings.ignore)
.filter(function() {
if (!this.name && validator.settings.debug && window.console) {
console.error("%o has no name assigned", this);
}
// select only the first element for each name, and only those with rules specified
if (this.name in rulesCache || !validator.objectLength($(this).rules())) {
return false;
}
// rulesCache[this.name] = true;
return true;
});
},
If you don't want to change in core library file. there is another solution. Just override existing core function.
$.validator.prototype.checkForm = function (){
this.prepareForm();
for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
if (this.findByName( elements[i].name ).length != undefined && this.findByName( elements[i].name ).length > 1) {
for (var cnt = 0; cnt < this.findByName( elements[i].name ).length; cnt++) {
this.check( this.findByName( elements[i].name )[cnt] );
}
}
else {
this.check( elements[i] );
}
}
return this.valid();
};

Categories