ModelValidator in ASP.NET MVC 2 Preview 2 – Part 2

In my last post we have discussed about the ModelMetaData and related classes along with a sample code.In this post we will discuss about ModelValidator and ModelValidatorProvider and extend the sample library.

  • ModelValidator – This is the abstract base class and implemented by custom validators to perform the model validation.It has a constructor as shown below:
    • protected ModelValidator(ModelMetadata metadata,ControllerContext controllerContext) – This is normally invoked from the classes implementing ModelValidator.It maintains a reference to the ControllerContext and ModelMetadata and exposes them as properties.

          The other important method of this class is:

  • public abstract IEnumerable<ModelValidationResult> Validate(Object container) – This is implemented by the derived class to validate the object.

Now let us look at the ConfigRequiredFieldValidator class my implementation of ModelValidator

    public class ConfigRequiredFieldValidator : ModelValidator
    {
        public ValidationMetaData  ValidationMetaInfo { get; set; }
        public ConfigRequiredFieldValidator(ConfigModelMetaData configmetadata,ControllerContext context,ValidationMetaData valmetadata)
            :base(configmetadata,context)
        {
            ValidationMetaInfo = valmetadata;
        }

        public override IEnumerable<ModelValidationResult> Validate(object container)
        {
            bool error = false;
            ConfigModelMetaData metadata = Metadata as ConfigModelMetaData;
            object val = metadata.Model;
            if (val != null)
            {
                if (this.Metadata.ModelType == typeof(System.String) && val.ToString().Length == 0)
                {
                    error = true;
                }
            }
            else
            {
                error = true;
            }
            if (error) yield return new ModelValidationResult{Message=ValidationMetaInfo.ErrorMessage};

        }
    }

In addition to the properties defined by ModelValidator I have maintained a reference to ValidationMetaData object and this is used set the Message property of ModelValidationResult if the validation fails.

Now to plugin this validator we need to take a look into the ModelMetaDataProvider class.This is another abstract base class with an abstract method:

  • public abstract IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata,ControllerContext context) – This method returns the ModelValidator’s based on ModelMetaData as shown in the sample implementation below:
     public class ConfigModelValidatorProvider : ModelValidatorProvider
    {
        public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)
        {
            List<ModelValidator> results = new List<ModelValidator>();
            ConfigModelMetaData configmetadata = metadata as ConfigModelMetaData;
            if (configmetadata.Validations  != null)
            {
                foreach (ValidationMetaData validation in configmetadata.Validations)
                {
                    if (validation.ValidationType == "Required")
                        results.Add(new ConfigRequiredFieldValidator(
                                    configmetadata,
                                    context,
                                    validation));
                }
            }
            return results;
        }
    }

Now the last thing that remains is to attach this custom validation provider at runtime.This is done by setting an instance of ConfigModelValidatorProvider to the Current property of ModelValidatorProviders class as shown below:

ModelValidatorProviders.Current = new ConfigModelValidatorProvider();

In the next post we will see how to use this plugin in an ASP.NET MVC Web Application

This entry was posted in Web App. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *