Jamie
Jamie

Reputation: 373

jQuery validate - how do I ignore letter case?

Probably a goofy question, but I can't seem to find anything in google land. I simply need one of my methods to ignore the case of the entered field. I am doing a city name match, but need both "Atlanta" and "atlanta" to be valid. How should I edit this to get the validation love that I need?

    jQuery.validator.addMethod("atlanta", function(value) {
    return value == "Atlanta"; //Need 'atlanta' to work too
}, '**Recipient must reside in Chicago City Limits**');

Pre thanks to any and all :)

Upvotes: 10

Views: 17713

Answers (5)

Juri
Juri

Reputation: 32900

You could even create a more generic jQuery validation rule which can be reused to perform a case insensitive comparison like

$.validator.addMethod("equalToIgnoreCase", function (value, element, param) {
        return this.optional(element) || 
             (value.toLowerCase() == $(param).val().toLowerCase());
});

which can then be used for the following two sample inputs

<input type="text" name="firstname"/>
<input type="text" name="username"/>

like

$("form").validate({
    rules: {
        firstname: {
           equalToIgnoreCase: "input[name=username]"
        }
    },
    messages: {
        firstname: {
           equalToIgnoreCase: "The 'firstname' must match the 'username'"
        }
    });

Upvotes: 16

Dmitriy Likhten
Dmitriy Likhten

Reputation: 5206

return (value ? value.match(/atlanta/i) : null) != null

This is case insensitive and you can do lots of fun stuff with the regex. Enjoy. And please don't do "Cosntant".toLowerCase() there is just too much wrong in that.

Upvotes: 1

amit_g
amit_g

Reputation: 31250

return value.toLowerCase() == "atlanta";
or use
return value.toLowerCase() == "Atlanta".toLowerCase();

Upvotes: 2

alex
alex

Reputation: 490153

jQuery.validator.addMethod("atlanta", function(value) {
    return value.toLowerCase() == "atlanta"; 
}, '**Recipient must reside in Chicago City Limits**');

Upvotes: 8

wagi
wagi

Reputation: 448

The easiest way to get a case-insensitive match is to convert both values to uppercase and then compare (uppercase because in certain cultures/languages the upper- to lowercase conversion can change a character!).

So make the check

value.toUpperCase() == "Atlanta".toUpperCase()

Upvotes: 7

Related Questions