Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC client-side e-mail validation doesn't work

In my registration form I want to put some client-side validations with MVC regular expressions, but it doesn't work... Here is part of model's code

        [Required]
        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid e-mail adress")]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email address*")]
        public string Email { get; set; }

But the message don't want to appear anyway... What is wrong here?

EDIT

In my View I have this

            <div>
            <div class="editor-label">
                @Html.LabelFor(m => m.Email)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.Email)
                @Html.ValidationMessageFor(m => m.Email)
            </div>
            </div>

And I've also include jQuery libraries in my layout

<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="/Content/Site.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
    <script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="/Scripts/jquery.validate.min.js"></script>
    <script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
    @RenderSection("Head")
</head>
like image 634
Chuck Norris Avatar asked Aug 30 '11 10:08

Chuck Norris


1 Answers

I've finally figured it out... Replacing Required attribute after RegularExpression attribute solved the problem)))

Instead this

        [Required]
        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid e-mail adress")]

        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email address*")]
        public string Email { get; set; }

now I have

        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid e-mail adress")]
        [Required]

        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email address*")]
        public string Email { get; set; }

And it now works perfectly!

like image 185
Chuck Norris Avatar answered Sep 23 '22 18:09

Chuck Norris