我有一個Model
其中有電話號碼和電子郵件MVC 4
。這就像註冊。因此,用戶可以提供電子郵件或手機號碼,或者兩者都提供。但是我不能讓他們選擇一個必需的領域。 我的模型就像如何在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
交替。我想寫一個作爲自定義必需字段的類。我已經通過這個問題,
- Question這裏的答案提供了一個解決方案與JavaScript結合。但我不會使用它。我將在這裏寫下類文件並實現我的邏輯。
RequiredIf
似乎是我的問題的確切建議,但我很累,嘗試該解決方案。我無法理解如何在我的項目中導入.dll。它是在Mvc 3中開發的- 另一個solution,但是在這裏他們將一個類中的可選屬性結合起來。所以我該怎麼做,因爲我的房產是完全分開的。那麼該怎麼辦。
第一個鏈接有什麼問題 - 這正是您所期望的。如果沒有提供「電子郵件」,則需要提供「MobileNo」,如果未提供「MobileNo」,則需要提供「電子郵件」。我假設在第二個選項中,你提到[萬無一失](http://foolproof.codeplex.com/)屬性? (它也有'[RequiredIfNot]') –
我不喜歡'javascript',因爲我不能顯示錯誤消息類似的與其他需要的錯誤。 Javascript以自己的方式顯示錯誤。 – gdmanandamohon
當然可以。這正是客戶端驗證如何使用'jquery.validate.js'和'jquery.validate.unobtrusive.js'工作的方式。 –