I’m developing a complex application with about 90 different forms (yeah, awesome). How do I go about doing complex field validation based on a few requirements:
1) field requirements are based on which user is logged in (role)
2) field requirements change if other data fields are answered differently (dynamic)
how is this accomplished in MVC4 using EF5 POCO’s?
I currently have created data annotations for required fields like so:
My EF5 POCO Model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(User_Validation))]
public partial class User
{
public int UserID { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
}
ValidationModels.cs file located with my EF5 POCO’s:
public class User_Validation
{
public int UserID { get; set; }
[Required(ErrorMessage = "The UserName is required")]
public string UserName { get; set; }
[Required(ErrorMessage = "The FirstName is required")]
public string FirstName { get; set; }
[Required(ErrorMessage = "The LastName is required")]
[Display(Name="Last Name")]
public string LastName { get; set; }
[Required(ErrorMessage = "The Password is required")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required(ErrorMessage = "The Email is required")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
}
This works fine and dandy, but how do I make my validations dynamic??
Thanks!
Do you need the admin to set the dynamic requirements for the responses or will they be fairly static from the outset?
If I was you I would create different action methods for each triggered response. This would allow you to specify the forms as partial views and render them based on the input logic.
If you need custom field validation it is recommended to write your own data validation framework. You can inherit from the ActionFilterAttribute which allows you to add custom validation before and after each action request/response cycle. Look here for some info Custom Filters in MVC
Additionally I would introduce a custom jquery validation framework for client side validation so that there is no multiple postbacks for the same form and then do you custom server side validation before generating the next form dynamically. For info an a framework look at this blog: Jquery – Custom Validation
Keep in mind that you don’t want a lot of chatting between your data store and view, so I would store as much of your configuration in a well thought out cache implementation.
I hope this helps.