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