自定义数据注释无效

时间:2017-07-17 11:28:24

标签: asp.net-mvc data-annotations

我在我的代码中为我的文本区域添加了以下自定义数据注释验证(仅允许有效的电子邮件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; }
   }

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

实际上,我有一个bootstrap模态形式,我在其中进行验证。点击“提交”按钮,内置自定义验证,例如“必填”。工作得很好。但是,我的自定义数据注释验证不起作用。我在这做什么错?

2 个答案:

答案 0 :(得分:0)

您应该检查控制器中的 def merchant_customers(merchant_id) do from u in User, join: b in subquery(user_merchant_balance()), on: u.id == b.user_id, where: b.merchant_id == ^merchant_id, select: %{u | balance: type(b.balance, Money.Ecto.Type)} end 值。 Model.IsValid如果任何验证失败(包括自定义验证),则返回Model.IsValid。所以你的控制器代码如下所示。

false

答案 1 :(得分: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