电子邮件地址客户端的MVC5验证

时间:2016-02-01 13:56:29

标签: asp.net-mvc validation

我的模型中有以下属性:

[Required(ErrorMessage = "{0} is a required field.")]
[StringLength(150, ErrorMessage = "There are too many characters in this field.")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
[MaxLength(150, ErrorMessage = "Maximum of 150 characters allowed.")]
[Display(Name = "Customer budget owner")]
public string CustomerBudgetOwner { get; set; }

所有属性都是来自microsoft的内置属性。 视图中的html如下所示:

 <div class="form-group">
  @Html.LabelFor(m => m.HardwareRequest.CustomerBudgetOwner, htmlAttributes: new { @class = "form-label" })
  <div class="input-group">
    <div class="input-group-addon input-group-sm">
      <span>@@</span>
    </div>
    @Html.TextBoxFor(m => m.HardwareRequest.CustomerBudgetOwner, htmlAttributes: new { @class = "form-control input-sm", id = "txtCustomerBudgetOwner" })
    <div class="input-group-addon">
      <span id="btnCustomerBudgetOwnerInfo" class="glyphicon glyphicon-info-sign info-icon" data-toggle="popover" data-placement="right" data-content="Enter the email address of the budget owner."></span>
    </div>
  </div>
  @Html.ValidationMessageFor(m => m.HardwareRequest.CustomerBudgetOwner, "", new { @class = "text-danger" })
</div>

如果我只输入几个字符但不输入@字符,则会显示验证错误消息。

如果我输入类似 aaaa@bbbbb.ccc 的内容,则不会出现错误,因为它看起来像是电子邮件地址。

如果我输入类似 aaaa @bbbbb 的内容,则不会显示客户端错误,但在控制器中,模型状态无效。

我是否在模型验证属性中出错? 还是我无法控制的其他东西?

[编辑] 删除DataType属性后,生成的HTML如下所示:

<input class="form-control input-sm valid" data-val="true" data-val-email="The Customer budget owner field is not a valid e-mail address." data-val-length="There are too many characters in this field." data-val-length-max="150" data-val-maxlength="Maximum of 150 characters allowed." data-val-maxlength-max="150" data-val-required="Customer budget owner is a required field." id="txtCustomerBudgetOwner" name="HardwareRequest.CustomerBudgetOwner" type="text" value="" aria-required="true" aria-invalid="false" aria-describedby="txtCustomerBudgetOwner-error">

这是文本框中的值:sdfsdfsdf @sdfsdfsdf

的ModelState:

enter image description here

1 个答案:

答案 0 :(得分:-1)

我也发现了这个问题,客户端和服务器端的验证规则不同。似乎奇怪的是,如果将数据注释应用于模型,您会期望行为一致。

说我有点犹豫-从技术上讲,客户端验证可能更准确,但这是极端情况。