简体   繁体   English

正则表达式在jQuery验证中不起作用

[英]Regular Expressions not Working in jQuery Validation

I'm having difficulty getting regular expressions to work with jQuery Validation. 我很难让正则表达式与jQuery Validation一起使用。 Suppose I take a simple regex that requires a minimum of 8 characters to match: 假设我使用一个简单的正则表达式,至少需要8个字符才能匹配:

(?=.{8,})

If plug this into a JavaScript-based regular expression tester , it works just fine. 如果将其插入基于JavaScript的正则表达式测试器 ,则可以正常工作。 8 or more characters match, 7 or less does not. 8个或更多字符匹配,7个或更少字符不匹配。

Further, if I test this in C# it works as well: 此外,如果我在C#中对此进行测试,它也可以正常工作:

        var regex = new Regex(@"(?=.{8,})");
        if (regex.IsMatch(myInput))
        {
            // Hits this code when myInput >= 8 characters
        }

Next, I use a ValidationAttribute in a view model to emit jQuery Validation to ensure that the user's input matches the expression: 接下来,我在视图模型中使用ValidationAttribute来发出jQuery Validation以确保用户输入与表达式匹配:

    [RegularExpression(@"(?=.{8,})", ErrorMessage="Does not match.")]
    public string MyInput { get; set; }

At this point, it breaks down. 在这一点上,它崩溃了。 No matter what I type in the field does not match. 无论我在字段中键入的内容都不匹配。 The HTML emitted is as follows: 发出的HTML如下:

    <input data-val="true" data-val-regex="Does not match." 
            data-val-regex-pattern="(?=.{8,})"  id="MyInput" name="MyInput"
            type="text" value="" />

I've tried different regular expressions, to no avail. 我尝试了不同的正则表达式,但无济于事。 Is there something different about regular expressions in jQuery Validation that I'm overlooking? 我忽略的jQuery验证中的正则表达式有什么不同吗?

Maybe this works: 也许这可行:

RegularExpression(@"^.{8,}$")

Hope this helps. 希望这可以帮助。 Cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM