简体   繁体   English

共享正则表达式(从C#到JS)-始终为假-这里出了什么问题?

[英]Shared regex (C# to JS) - Always false - what is wrong here?

I want to use the same regex for server side as client side but when I convert it over to JS it always returns false. 我想在服务器端和客户端使用相同的正则表达式,但是当我将其转换为JS时,它总是返回false。 I think the string literal is causing the issue but I am not seeing where. 我认为字符串文字引起了问题,但我看不到哪里。 I found this but still can't figure it out: Lost in translation - C# regex to JavaScript regex 我发现了这一点,但仍然想不通: 迷失了翻译-C#正则表达式到JavaScript正则表达式

Here is my server-side code: 这是我的服务器端代码:

public static string EmailRegex = @"^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";

Here is the razor: 这是剃须刀:

<input type="text" id="email" name="email" data-regex="@Model.EmailRegex" />

Here is the rendered HTML: 这是呈现的HTML:

<input type="text" id="email" name="email" data-regex="^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$">

Here is the JS code which gets called on $("#email").keyup(): 这是在$(“#email”)。keyup()上调用的JS代码:

function validateElementRegex(element) {
    var regex = $(element).data("regex");
    var value = $(element).val();
    return validateRegex(value, regex);
}

function validateRegex(value, regex) {
    if (typeof(value) === "undefined" || typeof(regex) === "undefined") {
        return false;
    }
    var regexType = typeof(regex);        // string e.g. "^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$"
    var pattern = new RegExp(regex, "i"); // tried with and without "i" - ignoreCase
    var patternType = typeof(pattern);    // object
    var result = pattern.test(value);     // always false

    return result;
}

Thanks 谢谢

Oh well you have an extra backslash in your regex: 哦,您的正则表达式中还有一个反斜杠:

^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$

The above regex matches email@myeamil\\.com 上面的正则表达式匹配email@myeamil\\.com

but it does not match email@myeamil.com 但与email@myeamil.com不匹配

It should be: 它应该是:

^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6}$

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

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