Maybe this is not the best code. If you have any recommendations, please let me know. Designed by @ MVC4
Model property with custom attribute
[CustomRemote("ValidateIP", "Validation", ErrorMessage = "Input is not a valid IP")]
Subclass RemoteAttribute
/// <summary> /// Custom Remote Attribute for Client an Server validation. /// </summary> public class CustomRemoteAttribute : RemoteAttribute { /// <summary> /// List of all Controllers on MVC Application /// </summary> /// <returns></returns> private static List<Type> GetControllerList() { return Assembly.GetCallingAssembly().GetTypes().Where(type => type.IsSubclassOf(typeof(Controller))).ToList(); } /// <summary> /// Constructor of base class. /// </summary> protected CustomRemoteAttribute() { } /// <summary> /// Constructor of base class. /// </summary> public CustomRemoteAttribute(string routeName) : base(routeName) { } /// <summary> /// Constructor of base class. /// </summary> public CustomRemoteAttribute(string action, string controller) : base(action, controller) { } /// <summary> /// Constructor of base class. /// </summary> public CustomRemoteAttribute(string action, string controller, string areaName) : base(action, controller, areaName) { } /// <summary> /// Overridden IsValid function /// </summary> /// <param name="value"></param> /// <param name="validationContext"></param> /// <returns></returns> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { // Find the controller passed in constructor var controller = GetControllerList().FirstOrDefault(x => x.Name == string.Format("{0}Controller", this.RouteData["controller"])); if (controller == null) { // Default behavior of IsValid when no controller is found. return ValidationResult.Success; } // Find the Method passed in constructor var mi = controller.GetMethod(this.RouteData["action"].ToString()); if (mi == null) { // Default behavior of IsValid when action not found return ValidationResult.Success; } // Create instance of the controller to be able to call non static validation method var instance = Activator.CreateInstance(controller); // invoke the method on the controller with value var result = (JsonResult)mi.Invoke(instance, new object[] { value }); // Return success or the error message string from CustomRemoteAttribute return (bool) result.Data ? ValidationResult.Success : new ValidationResult(base.ErrorMessageString); } }
Verification Controller Code
/// <summary> /// Controller for Client and Server validation /// <remarks>disable OutputCache</remarks> /// </summary> [OutputCache(Location = OutputCacheLocation.None, NoStore = true)] public class ValidationController : Controller { /// <summary> /// !!!!!!!!!!!!!!!!!! Needed for instance creation in custom attribute !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! /// </summary> public ValidationController() { } /// <summary> /// IP regex pattern of my choice /// </summary> const string IpPattern = @"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"; /// <summary> /// MAC regex pattern of my choice /// </summary> const string MacPattern = "^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$"; /// <summary> /// Validate IP /// </summary> /// <param name="ip">IP param is only submited on Serverside validation!!!</param> /// <returns>Validation Result</returns> public JsonResult ValidateIP(string ip) { // Check if ip and httpcontext is null to dodge NullReferenceException on Server side validation if (string.IsNullOrEmpty(ip) && HttpContext == null) { return Json(false, JsonRequestBehavior.AllowGet); } /* Use IP on Serverside validation * Use Querystring Param 0 to get IP from Client side vaildation without the need for the correct Id of input control */ string checkip = string.IsNullOrEmpty(ip) ? HttpContext.Request.QueryString[0] : ip; if (string.IsNullOrEmpty(checkip)) { return new JsonResult { Data = true, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } return new JsonResult { Data = Regex.IsMatch(checkip, IpPattern), JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } }
source share