jQuery Validation - Check if value matches label?
I am using the jQu开发者_运维问答ery Validation plugin on a form, and was wondering what's the easiest way of checking if the value of the input is the same as the label?
I'm using jQuery to take the text of each input's label and insert it as the default value of each form element, and then hide the label.
What I'm wanting to do is for the validation to fail if the form is submitted with the default input value unaltered.
Any ideas?
Thanks!
You can add a custom validate method (Need to test the code though) :-
$.validator.addMethod("value_label_same", function(value, element) {
var label = element.attr('label');
return label == value
}, "* Label and Value should match");
and use it to validate the field :-
value_label_same : true
Find the documentation here - http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage
This answer shows how to create a custom rule. Assuming that you're using <label>
s for your controls you'll be able to use a jQuery selector like $("label[for=" + $(element).id + "])
to get the label, and then compare the text to the value of the input.
There are a few ways to achieve this one is with a custom validator method I think you'll need to do something like this
There are many ways to get the label text
I'm assuming that you want the validation to fail if the label text = the value
$(function (){
jQuery.validator.addMethod(
"doesnotmatchlabel",
function(value, element) {
var label = $(element).closest('div.elHolder').find('label').text();
var result = ! label == value;
return this.optional(element) || result;
},
"required"
);
});
Also to add this method to your elements you might do this...
var textInputs= $('input:text');
if ( textInputs.length ){
textInputs.each(function (i,el){
var jqEl = $(el);
jqEl.rules( "add",
{"doesnotmatchlabel": true}
);
})
}
I don't think you need a plugin to do that.
$("input").each(function() {
$(this).blur(function(){
var labelvalue = $("label").text();
var inputvalue = $(this).val();
if(labelvalue === inputvalue) {
console.log("we have a match");
}
else { console.log("no match") }
})
});
精彩评论