简体   繁体   中英

@ symbol causing error with regex when using regex in javascript to validate email address

I'm trying to use javascript and regex to validate emails in my MVC view page.

I have the following javascript function:

function (input) {
    if (input.attr('name') === "user_name" && input.val() != "") {
        var pattern = "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
        return !!input.val().match(pattern);
    }
}

I'm using the same sort of function with another regex pattern and that one works but this one seems to be having an issue with the @ symbol. with the current pattern I keep getting the error:

"\\" is not valid at the start of a code block. Only identifiers, keywords, comments, "(" and "{" are valid.

I have tried updating the regex to have the part after the @ symbol surrounded by brackets but it still doesnt work. Any ideas how I can get this regex to work to validate emails?

I just wanted to post the answer so I can mark my question answered. The issue was that I needed to escape the @ in Razor with double @@.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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