How to check at least two words with jquery validation plugin?

后端 未结 1 834
忘了有多久
忘了有多久 2021-01-21 19:06

So i have this:

jQuery.validator.addMethod(\"tagcheck\", function(value, element) { 
  var space = value.split(\' \');
  return value.indexOf(\" \") > 0 &         


        
相关标签:
1条回答
  • 2021-01-21 19:47

    It has two spaces between the words:

    var string = "one  two";
    var space = string.split(" "); // ["one", "", "two"] There is a space between the first
    // space and second space and thats null.
    

    It has a space before the first character.

    var string = " foo bar";
    var location = value.indexOf(" "); // returns 0 since the first space is at location 0
    

    What you want is to use a regular expression.

    var reg = new RegExp("(\\w+)(\\s+)(\\w+)");
    reg.test("foo bar"); // returns true
    reg.test("foo  bar"); // returns true
    reg.test(" foo bar"); // returns true
    

    See .test and RegExp.

    \w matches any alphabetic character. \s matches any space character.

    Let's incorporate that into your code snippet for you:

    var tagCheckRE = new RegExp("(\\w+)(\\s+)(\\w+)");
    
    jQuery.validator.addMethod("tagcheck", function(value, element) { 
        return tagCheckRE.test(value);
    }, "At least two words.");
    
    0 讨论(0)
提交回复
热议问题