Search code examples
asp.net-mvcvalidationidataerrorinfo

using IDataErrorInfo in asp.net mvc


I've got a simple address entry app that I'm trying to use the IDataErrorInfo interface as explained on the asp.net site.

It works great for items that can be validated independently, but not so well when some items depend on others. For example, validating the postal code depends on the country:

    private string _PostalCode;
    public string PostalCode
    {
        get
        {
            return _PostalCode;
        }
        set
        {
            switch (_Country)
            {
                case Countries.USA:
                    if (!Regex.IsMatch(value, @"^[0-9]{5}$"))
                        _errors.Add("PostalCode", "Invalid Zip Code");
                    break;
                case Countries.Canada:
                    if (!Regex.IsMatch(value, @"^([a-z][0-9][a-z]) ?([0-9][a-z][0-9])$", RegexOptions.IgnoreCase))
                        _errors.Add("PostalCode", "Invalid postal Code");
                    break;
                default:
                    throw new ArgumentException("Unknown Country");
            }
            _PostalCode = value;
        }
    }

So you can only validate the postal code after the country has been set, but there seems to be no way of controlling that order.

I could use the Error string from IDataErrorInfo, but that doesn't show up in the Html.ValidationMessage next to the field.


Solution

  • For more complex business rule validation, rather than type validation it is maybe better to implement design patterns such as a service layer. You can check the ModelState and add errors based on your logic.

    You can view Rob Conroys example of patterns here

    http://www.asp.net/learn/mvc/tutorial-29-cs.aspx

    This article on Data Annotations ay also be useful.

    http://www.asp.net/learn/mvc/tutorial-39-cs.aspx

    Hope this helps.