I'm having trouble with my ASP.NET MVC 3 application. I have 2 propertiesin my model whereby I only want 1 of them required in my view based on whichever one is empty. So for example, if I enter a phone number then email is no longer required and vice versa, but if I leave both empty, then either 1 should be required, below is my model:
[Display(Name = "Contact Phone Number:")] [MaxLength(150)] public string ContactPhoneNumber { get; set; } [Display(Name = "Contact Email Address:")] [MaxLength(100)] public string ContactEmailAddress { get; set; }
Would I need to create a custom attribute to validate my model and if so, how would I achieve this?
See [Required] attribute for details about this attribute's behavior. [StringLength]: Validates that a string property value doesn't exceed a specified length limit. [Url]: Validates that the property has a URL format. [Remote]: Validates input on the client by calling an action method on the server.
Validation Error UI in ASP.NET MVCRun the application and navigate to the /Movies URL. Click the Create New link to add a new movie. Fill out the form with some invalid values. As soon as jQuery client side validation detects the error, it displays an error message.
Answer is "DataAnnotations"
You can implement IValidatableObject
on your class and provide a Validate()
method that implements your custom logic. Combine this with custom validation logic on the client if you prefer to ensure that one is supplied. I find this easier than implementing an attribute.
public class ContactModel : IValidatableObject { ... public IEnumerable<ValidationResult> Validate( ValidationContext context ) { if (string.IsNullOrWhitespace( ContactPhoneNumber ) && string.IsNullOrWhitespace( ContactEmailAddress )) { yield return new ValidationResult( "Contact Phone Number or Email Address must be supplied.", new [] { "ContactPhoneNumber", "ContactEmailAddress" } ); } } }
To get everything working at client side you'll need to add the following script to your view:
<script type="text/javascript"> $(function() { $('form').validate(); $('form').rules('add', { "ContactPhoneNumber": { depends: function(el) { return !$('#ContactEmailAddress').val(); } } }); }); </script>
Annotation-based conditional validation can be defined using ExpressiveAnnotations:
[RequiredIf("ContactPhoneNumber == null", ErrorMessage = "At least email or phone should be provided.")] public string ContactEmailAddress { get; set; } [RequiredIf("ContactEmailAddress == null", ErrorMessage = "At least email or phone should be provided.")] public string ContactPhoneNumber { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With