call today Call Today 320.281.0605

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.") %>
Share
  • http://aspdotnetmvc.com/blogs/default.aspx ASP.NET MVC Archived Blog Posts, Page 1

    [...] to Voteasp.net MVC 2 Validation – One Field Required (6/11/2010)Friday, June 11, 2010 from JoelI was building a form that had two fields: home phone number and [...]

  • Mark

    Any ideas on how to get both the Field1 and Field2 controls highlighted in red. That is, the control having the “input-validation-error” css applied to it as is the case when validation is performed on a single field(non-class level) in the model?

Agent Cody Banks 2 Destination London full lenght movie download Afghan Knights download movie Inside the Smiths download movie Beverly Hills Chihuahua download movie Permanent Vacation download movie Indiana Jones and the Kingdom of the Crystal Skull download movie Afghan Knights download movie Inside the Smiths download movie Beverly Hills Chihuahua download movie Permanent Vacation download movie Indiana Jones and the Kingdom of the Crystal Skull download movie