Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3: unobtrusive JavaScript validation

There are a lot of examples on how to "create your own model". Mark them with DataAnnotations. Scott Guthrie explains how to validate your model when using an ORM. What I don't find is when your model is actually coming in from an external DLL. How do you validate it?

Example:

/* Class coming in from an third-party DLL file. */
public class Person
{
    public string Name{get;set;}
    public int Age {get;set;}
}

The solution I am thinking of: Inherit the external class and then apply [MetadataType] to the inherited class.

[Metadata(typeof(Person2_Validation))]
public class Person2:Person{}

public class Person2_Validation
{
    [Required,Stringlength(50,ErrorMessage="Name required"]
    public string Name{get;set;}

    [RegularExpression("([0-9]+)")]
    public int Age
}

Is there a better way?

like image 318
ram Avatar asked Mar 22 '26 17:03

ram


1 Answers

You could create a model and use a Mapper (like AutoMapper or EmitMapper or ValueInjecter) to map between your objects, and validate against the mapped model.

When you need to transfer the object back you can map between your model to the recieved model.

This is very similar to a ViewModel approach in ASP.NET MVC.

So it's something like this:

Class A (the class from the DLL) Class B (your model)

You set all your annotations on B, and create whatever properties you need.

What you use is B. When you get something from the repository/source you map (copy all relevant values) A=>B and send it (let's say as a model in a View).

When you receive B back you validate it, and then map it the other way B=>A, and send it to the repository/service.

BTW: I would recommend using this approach even if model A was YOUR class.

Why use ViewModels instead of Domain Models in Views.

like image 147
Linkgoron Avatar answered Mar 25 '26 09:03

Linkgoron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!