【问题标题】:How to use dataannotation validation in asp.net mvc如何在 asp.net mvc 中使用 dataannotation 验证
【发布时间】:2015-06-16 13:52:26
【问题描述】:

我需要你的帮助,我已经编写了这个类来保存数据,在我的示例中,我使用了 DataAnnotation 进行验证,不幸的是我输入了无效的电子邮件地址,但它没有反对所以我我对使用 DataAnnotations

的正确方法感到困惑
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace workflow.DataHolders
{
    public class NewCompany
    {
        [Required]
        [StringLength(200, MinimumLength = 3, ErrorMessage="Length Should  Be More Than Three Letters")]
        public string CompanyName { get; set; }

        [Required]
        [EmailAddress(ErrorMessage="Invalid Email Address")]
        public string Email { get; set; }

        [Required]
        [StringLength(200, MinimumLength = 2, ErrorMessage = "Length Should  Be More Than Two Letters")]
        public string Country { get; set; }

        public string Description { get; set; }
    }
}

【问题讨论】:

  • 有效的电子邮件地址是什么意思?你能举个例子吗?
  • 看看这个答案,很好解释stackoverflow.com/a/26329350/4773983
  • @Ala 我编辑了,无效*
  • 你的意思是什么“它没有反对”?你在期待什么?您是否启用了客户端验证?您是否在视图中包含 @Html.ValidationMessageFor() 助手。你在 POST 方法中检查ModelState.IsValid 吗?

标签: asp.net asp.net-mvc data-annotations


【解决方案1】:

我们有两种方法可以做到这一点

第一种方式

[RegularExpression(@"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", ErrorMessage = "Invalid Email Address")]
public string email { get; set; }

第二种方式

 [DataType(DataType.EmailAddress)]
 [Email]
 public string email { get; set; }

【讨论】:

    猜你喜欢
    • 2015-05-02
    • 2013-01-15
    • 1970-01-01
    • 2011-09-11
    • 2013-04-12
    • 2023-03-09
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多