【问题标题】:How do I make an alternative required field in MVC 4 application?如何在 MVC 4 应用程序中创建替代必填字段?
【发布时间】:2017-08-27 21:05:44
【问题描述】:

我有一个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。我想编写一个作为自定义必填字段的类。我已经完成了这个问题,

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

【问题讨论】:

  • 第一个链接有什么问题 - 这正是您想要的。如果未提供Email,则需要提供MobileNo,如果未提供MobileNo,则需要提供Email。我假设在第二个选项中,您指的是 foolproof 属性? (其中还有一个[RequiredIfNot]
  • 我不喜欢javascript,因为我无法像其他必需的错误一样显示错误消息。 Javascript 以自己的方式显示错误。
  • 当然可以。这正是使用jquery.validate.jsjquery.validate.unobtrusive.js 进行客户端验证的工作原理

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


【解决方案1】:

我会选择解决方案 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; }

【讨论】:

  • 您的部分代码运行良好。但是,如果我在验证摘要中的两个实体上方写RequiredIfEmpty,它会显示一条消息 2 次。另一方面,如果我写在上面任何一个,它不会只标记单个输入字段,而不是突出显示两个输入框。
  • 这不会提供任何客户端验证。
  • 是的!正是@Stephen Muecke,表单提交后,它会返回验证错误。
  • @lazycoder - 这不是客户端验证,而是它的服务器端验证。为了实现客户端验证,该属性需要实现IClientValidatable,并且需要将规则添加到$.validator(根据您问题中的第一个链接)
  • 好的。我需要再次检查。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-15
  • 1970-01-01
  • 1970-01-01
  • 2014-07-29
  • 2019-01-10
相关资源
最近更新 更多