2017-07-17 85 views
0

我已经添加了以下自定义数据注释验证我的代码为我的文字区域(只允许有效的电子邮件ID自定义数据标注工作不

public class ValidateEmails : ValidationAttribute 
{ 
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     if (value != null) 
     { 
      string[] commaLst = value.ToString().Split(','); 
      foreach (var item in commaLst) 
      { 
       try 
       { 
        System.Net.Mail.MailAddress email = new System.Net.Mail.MailAddress(item.ToString().Trim()); 

       } 
       catch (Exception) 
       { 
        return new ValidationResult(ErrorMessage = "Please enter valid email IDs separated by commas;"); 
       } 
      } 
     } 
     return ValidationResult.Success; 
    } 

} 

型号:

public class BuildModel 
{ 
    public Int64 ConfigID { get; set; } 

    [Required(ErrorMessage = "Please select a stream!")] 
    public string StreamName { get; set; } 

    [Required(ErrorMessage = "Please select a build location!")] 
    public string BuildLocation { get; set; } 

    public string Type { get; set; } 

    public bool IsCoverity { get; set; } 

    [ValidateEmails(ErrorMessage = "NOT VALID !!!")] 
    public string EmailIDsForCoverity { get; set; } 
    } 

当我运行我的应用程序并在文本区域中输入无效的字符串时,断点会在验证内部发生。但是,提交行为仍然会发生。

实际上,我有一个引导模式窗体,我在其中进行验证。点击提交按钮,内置的自定义验证,如“必需”,效果很好。但是,我的自定义数据注释验证不起作用。我在这里做什么错了?

+1

你的'Model.IsValid'在你的行动检查? – DavidG

+0

你可以使用'RegularExpression'验证器为此和正则表达式为逗号分隔验证是'(([[A-ZA-Z0-9 _ \ - \。] +)@((\ [[0-9] {1,3 } \ [0-9] {1,3} \ [0-9] {1,3} \)|。。。(([A-ZA-Z0-9 \ - ] + \)+))( (\ s *; \ s * | \ s * $))* '请检查[a-zA-Z] {2,4} | [0-9] {1,3})这个答案](https://stackoverflow.com/a/9809636/2534646)获取更多信息 – Curiousdev

+0

你的属性需要实现'IClientValidatable',如果你需要写脚本来将规则添加到'$ .validator'想要客户端验证。 –

回答

0

您应该检查控制器中的Model.IsValid值。 Model.IsValid返回false如果任何验证失败(包括自定义验证)。所以你的控制器的代码如下所示。

[HttpPost] 
    public virtual ActionResult Index(BuildModel viewModel) 
    { 

    if (ModelState.IsValid) 
    { 
     // Your Custom code... 
    } 

    return View(viewModel); 
    } 
+0

但我需要它仅在客户端进行验证。 – Ponni

+1

然后你应该使用jQuery验证。自定义验证工作在服务器端。 – CommonPlane

0

您的代码应与此类似:

[Display(Name = "Email address")] 
[Required(ErrorMessage = "The email address is required")] 
[EmailAddress(ErrorMessage = "Invalid Email Address")] 
public string Email { get; set; } 

来源:Email address validation using ASP.NET MVC data type attributes

+0

我的输入将使用逗号分隔的电子邮件ID,而不是单个电子邮件ID。 – Ponni