开发者

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>


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!


You also need

1.@Html.ValidationMessageFor(m => m.Email) in the view where you want the message to appear

2.Include the JavaScript files required for client side validation. If you are using unobtrusive validation then this will be

jQuery, 
jQuery validate, 
jQuery validate unobtrusive 

in that order.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜