在我的视图上使用数据注释时,电子邮件验证不起作用?

问题描述 投票:0回答:1

我有一封同时为模型和视图创建的电子邮件,究竟是什么问题?当我检查此错误时,我没有从浏览器中看到任何错误,以下是我使用asp.net mvc在表单上进行此验证的逻辑。

                        <div class="row">
                        <label for"Email">Email:</label>
                        <div class="input-group col-md-4 col-md-offset-2 col-sm-2 col-xs-2">
                            <div class="input-group pull-right">
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                @Html.TextBoxFor(m => m.Email, new { @class = "form-control", type = "email", id = "inputEmail" , placeholder = "[email protected]", 
                                required = "required",
                                 pattern = @"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$", title = "This field is required"})
                                @Html.ValidationMessageFor(m => m.Email, " ", new { @class = "text-danger" })
                                <div class="input-group-append">
                                    <div class="input-group-text">

                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

        // Model
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }
asp.net-mvc bootstrap-4 data-annotations
1个回答
0
投票

您为什么在视图中写入PatternRequired? DataAnnotations不应该这样做吗?试试:

[Required]
[Display(Name = "Email")]
[RegularExpression("^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))\z", ErrorMessage = "Please enter a valid email address")]

然后在视图中:

@Html.TextBoxFor(m => m.Email)
© www.soinside.com 2019 - 2024. All rights reserved.