Blog
asp.net MVC 2 Validation – One Field Required
June 11, 2010 Author: Joel
I was building a form that had two fields: home phone number and mobile phone number.
The client needed at least one of the two fields filled out.
Given the existing DataAnnotations nothing fit the bill in this case. I ended up creating a custom validation attribute that is applied at the class level.
I based it off of the PropertiesMustMatchAttribute custom attribute that is included in the AccountModels.cs/vb file within the default ASP.NET MVC 2 application project template (just do a File->New ASP.NET MVC 2 Web Project within VS 2010 and look for this class).
First off in the ContactModel.cs I added:
using System.ComponentModel.DataAnnotations; using System.Globalization;
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class OneOrOtherFieldRequired : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' or '{1}' are required.";
private readonly object _typeId = new object();
public OneOrOtherFieldRequired(string field1, string field2)
: base(_defaultErrorMessage)
{
Field1 = field1;
Field2 = field2;
}
public string Field1 { get; private set; }
public string Field2 { get; private set; }
public override object TypeId
{
get
{
return _typeId;
}
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, Field1, Field2);
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
object field1 = properties.Find(Field1, true).GetValue(value);
object field2 = properties.Find(Field2, true).GetValue(value);
string valueAsString1 = field1 as string;
string valueAsString2 = field2 as string;
if (String.IsNullOrEmpty(valueAsString1) && String.IsNullOrEmpty(valueAsString2))
{
return false;
}
return true;
}
}
I then created in ContactModel.cs the ContactModel class. In this class I have among other properties the two phone number properies: HomePhoneNumber and MobilePhoneNumber.
[OneOrOtherFieldRequired("HomePhone", "MobilePhone", ErrorMessage="Please fill in either your home or mobile number.")]
public class ContactModel
{
...
public String HomePhone { get; set; }
public String MobilePhone { get; set; }
In the ContactController I have an action:
[HttpPost]
public ActionResult Index(Contact contact)
{
if (ModelState.IsValid)
{
contact.Store();
contact.SendEmail();
ViewData["ShowForm"] = false;
return View();
}
ViewData["ShowForm"] = true;
return View(contact);
}
When creating the view make sure to create a strongly typed view on the ContactModel
In the View I add the validation summary to display the error message if the requirement isn’t fulfilled.
<%= Html.ValidationSummary(true, "Please correct invalid and required fields.") %>
-
http://aspdotnetmvc.com/blogs/default.aspx ASP.NET MVC Archived Blog Posts, Page 1
-
Mark
-
Categories
- asp.net (12)
- Blog (3)
- Business (5)
- Conferences (1)
- Errors (5)
- Office (1)
- Portfolio (3)
- Reviews (3)
- SEO (4)
- SQL Server (4)
- Tips (2)
- Uncategorized (2)
- Web Development (14)
-
Archives