jQuery validate - how do I ignore letter case?

后端 未结 5 2170
无人共我
无人共我 2021-02-20 16:08

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 mat

相关标签:
5条回答
  • 2021-02-20 16:17
    return value.toLowerCase() == "atlanta";
    or use
    return value.toLowerCase() == "Atlanta".toLowerCase();
    
    0 讨论(0)
  • 2021-02-20 16:21
    jQuery.validator.addMethod("atlanta", function(value) {
        return value.toLowerCase() == "atlanta"; 
    }, '**Recipient must reside in Chicago City Limits**');
    
    0 讨论(0)
  • 2021-02-20 16:27

    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()
    
    0 讨论(0)
  • 2021-02-20 16:34

    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'"
            }
        });
    
    0 讨论(0)
  • 2021-02-20 16:34
    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 讨论(0)
提交回复
热议问题