【发布时间】: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; }
}
这里我想交替使用Email 和PhoneNo。我想编写一个作为自定义必填字段的类。我已经完成了这个问题,
【问题讨论】:
-
第一个链接有什么问题 - 这正是您想要的。如果未提供
Email,则需要提供MobileNo,如果未提供MobileNo,则需要提供Email。我假设在第二个选项中,您指的是 foolproof 属性? (其中还有一个[RequiredIfNot]) -
我不喜欢
javascript,因为我无法像其他必需的错误一样显示错误消息。 Javascript 以自己的方式显示错误。 -
当然可以。这正是使用
jquery.validate.js和jquery.validate.unobtrusive.js进行客户端验证的工作原理
标签: asp.net-mvc validation asp.net-mvc-4 requiredfieldvalidator