如何在MVC 4应用程序中创建替代必填字段?

时间:2017-04-03 05:35:52

标签: asp.net-mvc validation asp.net-mvc-4 requiredfieldvalidator

我有一个Model,其中包含MVC 4中的电话号码和电子邮件。就像注册一样。因此,用户可以提供电子邮件或手机号码或两者。但是我无法做出替代必需的领域。 我的模型就像

public class RegisterModel
    {
        [Required]
        [Display(Name = "User name")]        
        [UsernameValidator(ErrorMessage = "Only Letters and numbers")]
        [System.Web.Mvc.Remote("IsUserExitst", "Account", HttpMethod = "POST", ErrorMessage = "This user name already exists. Try a new one.")]
        public string UserName { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        [Required]
        [MaxLength(50)]
        [EmailOrPhoneValidator(ErrorMessage = "Invalid Phone number")]
        [Display(Name = "Phone number")]
        [System.Web.Mvc.Remote("IsMobOrEmailExists", "Account", HttpMethod = "POST", ErrorMessage = "This Phone number or Email already exists. Try a new one.")]
        public string MobileNo { get; set; }


        [Required]
        [MaxLength(50)]
        [EmailAddress(ErrorMessage = "Invalid Email address")]
        [Display(Name = "Email")]
        [System.Web.Mvc.Remote("IsEmailExists", "Account", HttpMethod = "POST", ErrorMessage = "This Email already exists. Try a new one.")]
        public string Email { get; set; }
    }

我想在此处使用EmailPhoneNo。我想编写一个作为Custom required字段的类。我已经完成了这个问题,

  1. Question这里的答案提供了一个结合javascript的解决方案。但我不会用它。我将在此处写下类文件并实现我的逻辑。
  2. RequiredIf似乎是我的问题的确切建议,但我很累,尝试解决方案。我无法理解如何在我的项目中导入.dll。它是在Mvc 3中开发的
  3. 另一个solution,但在这里他们将一个替代属性组合在一起。所以我该如何做,因为我的属性是完全分开的。那么该怎么办。

1 个答案:

答案 0 :(得分:2)

我会使用解决方案2并创建一个RequiredIf验证属性。无需导入任何DLL,因为您可以自己创建类。以下是属性的外观示例。它来自我在我自己的代码中使用的RequiredIfTrue属性,我交换了验证逻辑以查找空值

public class RequiredIfEmpty : ValidationAttribute
{
    private string _fieldName;

    public RequiredIfEmpty(string fieldName)
    {
        _fieldName = fieldName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(_fieldName);
        if (property == null)
        {
            throw new ArgumentException("No property with the name " + _fieldName + " found.");
        }

        string fieldValue = (string)property.GetValue(validationContext.ObjectInstance, null);
        if (String.IsNullOrWhiteSpace(fieldValue))
        {
            return (value != null && !String.IsNullOrWhiteSpace((string)value) ? ValidationResult.Success : new ValidationResult(ErrorMessage));
        }
        else
        {
            return ValidationResult.Success;
        }
    }
}

在ViewModel中,您可以像使用任何其他属性一样使用该属性,但必须指定备用属性的名称

[RequiredIfEmpty("Email", ErrorMessage = "Phone number invalid")]
[MaxLength(50)]
[Display(Name = "Phone number")]
[System.Web.Mvc.Remote("IsMobOrEmailExists", "Account", HttpMethod = "POST", ErrorMessage = "This Phone number or Email already exists. Try a new one.")]
public string MobileNo { get; set; }