2017-07-17 35 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