MVC form Validation

I have went through most of the form validation for mvc like IDataErrorInfo, Xval, ValidationToolkit etc.
This is specific with phone numbers or credit card validation where your model will have a property called "Phone" or "CreditCardNumber" but the UI/view will display the values in three text boxes( by splitting 3-3-4 in each text box).
So how to get these three inputs in "Phone" field and validate them separately in the model like

  1. First input – cannot start with 0
  2. second input – should have 3 numbers.
  3. third input – should have 4 numbers.

then display/add error style for all of the three textboxes using any of the above given validations( prefer to use IDataErrorInfo)

Let me know if any other thread has solutions.

Thanks in advance.

Best Solution

Can I clarify your question? Are you asking how to split a single model property up into multiple display parts for the UI, and at the same time retain knowledge of the multiple parts when your model self-validates the single property?

I think these are two different problems. The latter is a simple regular expression validation problem that can be applied to your model validation. For example, the Validation Application Block provides support for this. Check out this David Hayden blog.

The former can be solved with a specific custom model binder which re-constitutes the three fields. That is a nice and clean approach. Alternatively you could just glue them together yourself from the FormCollection values.

However, you should regard the two problems as distinct: your model will always want to be able to validate itself irrespective of where the data has come from (GUI, web service, file import etc.) and the three field split is just a requirement of that particular web page.