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

Oct 4th, 2009 | By | Category: Web Apps

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


Kick It on DotNetKicks.com
Tags:
  • http://scriptsrss.com/modelvalidator-in-aspnet-mvc-2-preview-2-%e2%80%93-part-2-coding-n-design/ ModelValidator in ASP.NET MVC 2 Preview 2 – Part 2 – Coding N Design Scripts Rss

    [...] is the original:  ModelValidator in ASP.NET MVC 2 Preview 2 – Part 2 – Coding N Design By admin | category: asp.net script | tags: asp, config, mvc, net, plugin, the-next, [...]

  • http://www.netdeluxo.com/blog/programming/asp-programming/modelvalidator-in-asp-net-mvc-2-preview-2-%e2%80%93-part-2-coding-n-design/ ModelValidator in ASP.NET MVC 2 Preview 2 – Part 2 – Coding N Design | Webmaster Tools

    [...] Read the rest here: ModelValidator in ASP.NET MVC 2 Preview 2 – Part 2 – Coding N Design [...]

  • http://sovit.biz/modelvalidator-in-aspnet-mvc-2-preview-2-%e2%80%93-part-2-coding-n-design/ ModelValidator in ASP.NET MVC 2 Preview 2 – Part 2 – Coding N Design

    [...] post:  ModelValidator in ASP.NET MVC 2 Preview 2 – Part 2 – Coding N Design SHARETHIS.addEntry({ title: "ModelValidator in ASP.NET MVC 2 Preview 2 – Part 2 – Coding N [...]

  • http://blog.cwa.me.uk/2009/10/05/the-morning-brew-447/ Reflective Perspective – Chris Alcock » The Morning Brew #447

    [...] 2 Preview 2. This first part looks at the Model Metadata and Model Metadata Provider interface, and Part 2 continues with a look at the Model Validator and ModelValidator [...]

  • Johan Nilsson

    Ah great reading! Looking forward, looking forward!

  • Johan Nilsson

    Ah great reading! Looking forward, looking forward!

  • http://samgentile.com/Web/new-and-notable/new-and-notable-377/ New and Notable 377 : Sam Gentile’s Blog (if (DeveloperTask == Communication && OS == Windows)

    [...] ModelValidator in ASP.NET MVC Preview 2 – Part 2 - The second part discusses ModelValidator and ModelValidatorProvider [...]

  • http://aspdotnetmvc.com/blogs/default.aspx ASP.NET MVC Archived Blog Posts, Page 1

    [...] to VoteModelValidator in ASP.NET MVC 2 Preview 2 – Part 2 (10/3/2009)Saturday, October 03, 2009 from codingndesign.comIn the next post we will see how to use this plugin [...]

  • http://www.tryideas.com.br/ Giovanni

    part 3 plz :)