开发者

jQuery validate - how do I ignore letter case?

开发者 https://www.devze.com 2023-02-13 07:08 出处:网络
Probably a goofy question, but I can\'t seem to find an开发者_StackOverflowything 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,

Probably a goofy question, but I can't seem to find an开发者_StackOverflowything 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 :)


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'"
        }
    });


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


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()


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号