I'm trying to add the same rules to html input elements with this naming convention:
name="elements[1]"
name="elements[2]"
I'm using jQuery and jQuery Validation Plugin:
var elements = $("#elementsFieldset :input");
$.each(elements, function(i, element) {
element.rules('add', {
required: true,
number: true
});
But I'm afraid that element is not the kind of object jQuery expects for adding rules.
I'm receiving:
Uncaught TypeError: Object #<HTMLInputElement> has no method 'rules'
Many thanks for any help.
Use $(this) instead of element.
element is HTML JavaScript Object.
to add rules you need jQuery Object i.e $(this)
var elements = $("#elementsFieldset :input");
$.each(elements, function(i, element) {
$(this).rules('add', {
required: true,
number: true
});
or even better
var elements = $("#elementsFieldset :input");
elements.each(function(){
$(this).rules('add', {
required: true,
number: true
});
Updated
Below code works for one element only if you want to apply rule for more than one element use .each() as used in above example.
$("#elementsFieldset :input").rules("add", {
required:true,
number:true
});
Read jQuery Validation Plugin - adding rules that apply to multiple fields commented by Sparky
jQuery Validation Plugin
Try this,
$.each(elements, function(i, element) {
$(this).rules('add', {// use $(this) instead of element
required: true,
number: true
});
or try it simply,
$("#elementsFieldset :input").rules("add", {
required:true,
number:true
});
You can add rule on a class See jQuery Validation using the class instead of the name value
Related
Consider this application of the jQuery validation plugin:
(function($) {
'use strict';
$('form[data-behavior="validate"]').validate({
errorElement: 'span',
ignore: ':hidden, .select-dropdown',
normalizer: function(value) {
if (!value) value = '';
if ($(this).is('[data-currency-mask]')) {
return value.replace(/\$/g, '').replace(/,/g, '');
}
return value;
},
highlight: function(element) {
$(element).addClass('invalid');
$(element.form).find('label[for=' + element.id + ']').addClass('invalid');
},
unhighlight: function(element) {
$(element).removeClass('invalid');
$(element.form).find('label[for=' + element.id + ']').removeClass('invalid');
}
});
})(jQuery);
This custom validator adds/removes the error class "invalid" to/from both the element and its label. The result looks like this (where Materialize.css is used):
There is some code repetition in the highlight and unhighlight functions, which I'd like to eliminate; in addition, it seems like I could make use of the errorClass attribute (cf. https://jqueryvalidation.org/validate/) instead of hard-coding 'invalid' everywhere.
I've tried setting errorClass: 'invalid' in the object passed to .validate(), and then using errorClass instead of 'invalid' in the highlight and unhighlight methods, but this appears not to work. How can I refactor this code?
I don't have enough reputation to comment because people won't flame my answers or what ever it takes to get reputation.
But, the first thing I notice is
if (!value) value = '';
should be
if (!value) { value = ''; }
which could also be initialized with
value = value || '';
or, depending what version of ECMAscript you're using, you could even save a line of code and initialize it in the parameters
normalizer: function(value = '')
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters
Calling the strike function (after the select) function, I get the following error:
Uncaught ReferenceError: selected is not defined
methods: {
select: function(event) {
selected = event.target.id
},
strike: function(event) {
$(selected).toggleClass('strike')
}
}
This works using JavaScript, document.getElementById(selected).classList.add('strike') but not JQuery.
How to I define selected for jQuery to access?
Instead of having to query the DOM again, it'd be better if you save a reference to the actual element:
methods: {
select: function(event) {
this.selected = event.target;
},
strike: function() {
$(this.selected).toggleClass('strike');
}
}
If you don't have to support old IE browsers, you can forgo jQuery here completely by using the classList property:
methods: {
select: function(event) {
this.selected = event.target;
},
strike: function() {
this.selected.classList.toggle('strike');
}
}
Finally, there should be a way to handle all this through Vue's :class binding in the template itself. If you'd show us the template, we may help you improve it.
Because $() is expecting a CSS selector string. Add # to denote it is an id.
$("#" + selected).toggleClass('strike')
I'm trying to validate a group of input arrays using jquery validator plugin. I'm having problems understanding how to pass another element into the validation.
My code so far:
$('#edit-fixtures').validate({
rules: {
"player_a[]": {
required: true,
uniqueMatch: function () {
return $(this).next('.player').val();
},
},
"player_b[]": {
required: true,
uniqueMatch: function () {
$(this).closest('.player').val();
},
},
}
});
My input elements are a series of paired select boxes named player_a[] player_b[] There are about 40 pairs. Each pair should be unique and that's what i'll be validating.
I'm trying to pass the value of the nearest player_b to the changed player_a and vice versa.
I have a change method to validate on each change:
$(".player").change(function () {
var check = $(this).valid();
console.log("validation:", check);
});
I'm still working on the validation method but cant seem to get the parameters to the method correctly.
Is there a way of doing this?
uniqueMatch: [$item1, $item2, ....]
$.validator.addMethod('uniqueMatch', function(value, element, parameterValue) {
var item1Value = $(parameterValue[0]).val();
//and so on...
//Based on values, you return true or false;
//Voila!
}
I've a form where I'm having some fields and then if needed user can add more fields of same type. Im using http://jqueryvalidation.org/ validate plugin to validate fields.
As I read somewhere jquery validate plugin requires unique names to fields for validating them. So i'm naming each field uniquely. First I hoped that validate plugin will take care of dynamically added element's validation if I add rules using classes. But it turns out it does not.
So even if name of each field is unique, validate plugin validates only first input which was rendered initially.
I even tried using $.clone() in hope that it'll take care of all event bindings. But it did not worked for me. So I moved to underscore to repeat the markup as there are number of fields and I don't want to write templates in JS and name accordingly.
I can't find a solution to this and stuck here. Can't more on until this issue is resolved.
Here's JS that I've written.
$("#work_form").validate();
$(".work_emp_name").rules("add", {
required: true
});
_.templateSettings.variable = "element";
var tpl = _.template($("#form_tpl").html());
var counter = 1;
$("form").on("click", ".add_employer", function (e) {
e.preventDefault();
var tplData = {
i: counter
};
$("#word_exp_area").append(tpl(tplData));
counter += 1;
});
Please find markup in fiddle set up.
example and code set up here
When using one of the methods from this plugin, like .rules(), and targeting more than one element, like a class, you must also use the jQuery .each() method.
$('.work_emp_name').each(function () {
$(this).rules("add", {
required: true
});
});
And you cannot use .rules() on elements that don't yet exist in the DOM. Simply move the .rules() method to inside the function that creates your new inputs.
$("form").on("click", ".add_employer", function (e) {
e.preventDefault();
var tplData = {
i: counter
};
$("#word_exp_area").append(tpl(tplData));
counter += 1;
$('.work_emp_name').each(function () {
$(this).rules("add", {
required: true
});
});
});
Working DEMO: http://jsfiddle.net/Yy2gB/10/
However, you can make it more efficient by only targeting the one new field, instead of all fields with the work_emp_name class.
$("form").on("click", ".add_employer", function (e) {
e.preventDefault();
var tplData = {
i: counter
};
$("#word_exp_area").append(tpl(tplData)); // <- add new field
$('input[name="work_emp_name['+counter+']"]').rules("add", { // <- apply rule to new field
required: true
});
counter += 1;
});
Working DEMO: http://jsfiddle.net/Yy2gB/11/
Both of my examples above are for adding rules to the dynamically created fields. You'll still need to declare any rules for your static fields upon dom ready as follows...
$("#work_form").validate({
rules: {
"work_emp_name[0]": {
required: true
}
}
});
Returns the validations rules for the first selected element or
Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is, $( “form” ).validate() is called first or
Removes the specified rules and returns all rules for the first matched element.
more info
function addRule(id){
$("[name='work_emp_name["+id+"]']").rules("add", {
required: true
});
}
$("#work_form").validate();
addRule(0);
_.templateSettings.variable = "element";
var tpl = _.template($("#form_tpl").html());
var counter = 1;
$("form").on("click", ".add_employer", function (e) {
e.preventDefault();
var tplData = {
i: counter
};
$("#word_exp_area").append(tpl(tplData));
addRule(counter);
counter += 1;
}); here
That's because jQuery Validation only validates the first occurrence of the array currently.
You can check my commit on the plugin that will just work fine on any occurrence of the named array.
Thank you in advance for looking at this. :-)
The form validation itself works on other items where the field is simply required - that is no problem.
I am trying to set a numeric range for validation from my autocomplete dynamically.
I am using the bassistance.de JQuery validation found here.
Upon the select, I am calling a function, but it needs to be added to .validate() code instead of its own function (I think), but now sure how to combine them.
The autocomplete is a generic function that is called by multiple inputs.
<script>
$().ready(function() {
// validate the form when it is submitted
$("#form4100").validate();
});
</script>
<script>
function Autocomplete(numberLocation,nameLocation,dscLocation,chargeLocation,amountLocation) {
select: function( event, ui ) {
$(numberLocation).val( ui.item.value );
$(nameLocation).html( ui.item.desc );
alert("Minimum Investment: "+ui.item.minimum);
setvalidation(amountLocation,ui.item.minimum);
return false;
}
}
function setvalidation(amountLocation,minimum){
alert("validation function launched");
amountLocation.validate({
rules: {
field: {
required: true,
range: [minimum, 5000000]
}
}
});
}
</script>
Thanks!
I found out (after reading the docs further on the validation plugin) that there is a .rules add method. So the .select can call this function:
function setvalidation(amountLocation,minimum){
amountLocation.rules("add",{
required: true,
range: [minimum, 5000000],
messages: {
range: "$ "+minimum + " Minimum"
}
});
}