最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Validating email addresses using regular expression with Razor syntax - Stack Overflow

programmeradmin0浏览0评论

I am using Razor syntax and trying to use a regular expression to validate email address; here is the validation function:

function validateEmail(txtEmail){
   var a = document.getElementById(txtEmail).value;
   var filter = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{0,4}$/;
    if(filter.test(a)){
        return true;
    }
    else{
        return false;
    }
}​

but since the regular expression has an @ sign, Razor thinks it's part of it syntax and gives me an error.

Is there anyway to avoid to make sure razor disregards the @ sign in JavaScript ?

I am using Razor syntax and trying to use a regular expression to validate email address; here is the validation function:

function validateEmail(txtEmail){
   var a = document.getElementById(txtEmail).value;
   var filter = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{0,4}$/;
    if(filter.test(a)){
        return true;
    }
    else{
        return false;
    }
}​

but since the regular expression has an @ sign, Razor thinks it's part of it syntax and gives me an error.

Is there anyway to avoid to make sure razor disregards the @ sign in JavaScript ?

Share Improve this question edited Jan 23 at 21:06 TylerH 21.1k77 gold badges79 silver badges112 bronze badges asked Mar 6, 2012 at 19:05 COLD TOLDCOLD TOLD 13.6k3 gold badges36 silver badges52 bronze badges 1
  • See Escape @ character in razor view engine. Alternatively you can put Javascript in a separate file. – oleksii Commented Mar 6, 2012 at 19:09
Add a comment  | 

3 Answers 3

Reset to default 13

Unicode may work like this

string filter = "/^[a-zA-Z0-9_.-]+\\u0440[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{0,4}$/";

Alternatively in razor @@ is a normal @ symbol, it should work in your javascript.

string filter = "/^[a-zA-Z0-9_.-]+@@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{0,4}$/";

try this may be help you

function validateEmail(email) { 
    var re = /^[_a-z0-9-A-Z-]+(\.[_a-z0-9-A-Z-]+)*@[a-z0-9-A-Z-]+(\.[a-z0-9-A-Z-]+)*(\.[a-z]{2,4})$/;
    return re.test(email);
} 

It is common to check the format of the email is valid or not. To validate email address we need to use regular expression. In MVC razor we should use @@ symbol to perform validation.

MVC Razor syntax:

var emailRegEx = /^(([^<>()[\]\\.,;:\s@@\"]+(\.[^<>()[\]\\.,;:\s@@\"]+)*)|(\".+\"))@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

Normal HTML:

For normal we should use @ symbol to perform validation

var emailRegEx = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
发布评论

评论列表(0)

  1. 暂无评论