Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create custom DataType Validation

I want to make my own validation class (i have a lot of validation methods in JS that i want to translate into C# to use with MVC models) that works exactly like data annotations do, validating in client and server side: [DataType(MyDataType)] or like a Validation DataAnnotation Attribute like this: [MyDataTypeValidation]

i don't know wich option is better to make my validation "library"

In example i have my class FigurasDA and i want to make my custom validation to the attribute nombre.

namespace MonitoreoIntegrado.Models
{
    [MetadataType(typeof(FigurasDA))]
    public partial class Figuras
{
}

public class FigurasDA
{
    [DataType(MyDataType)]
    //or
    [MyDataTypeValidation]
    public string nombre { get; set; }
}
}

so in this case, i want to validate that the string matches the regexp @"^[\w\s\.\-_]+$" and shows a error message like this "Solo se permite letras, numeros y puntuaciones(- _ .)" if don't. (this is my "Alfanumerico" datatype).

Can you give me an example where to put my validation class and what code write inside?.

like image 504
Clamari Avatar asked Jun 13 '14 18:06

Clamari


People also ask

How do I create a custom validation attribute?

To create a custom validation attributeUnder Add New Item, click Class. In the Name box, enter the name of the custom validation attribute class. You can use any name that is not already being used. For example, you can enter the name CustomAttribute.

How do I use CustomValidationAttribute?

You apply the CustomValidationAttribute attribute to an entity or one of its members when you need to specify a method to use for validating the entity or the value of the member. Using the first overload is the same as defining custom validation logic for an individual value.


1 Answers

Actually it's easy... You just have to inherit you custom validation attribute from ValidationAttribute class and provide your own IsValid logic. For example:

public class MyDataTypeValidationAttribute : ValidationAttribute
{
    private Regex _regex = new Regex(@"^[\w\s.-_]+$");          

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {               
        if (_regex.IsMatch(value.ToString()))
        {
            return ValidationResult.Success;
        }

        return new ValidationResult("Solo se permite letras, numeros y puntuaciones(- _ .)" );
    }
}

and in your view model you can use:

public class FigurasDA
{    
    [MyDataTypeValidation]
    public string nombre { get; set; }
}

You can save this validation attribute, for example in Attributes folder in your MVC project:

Step 1

Step 2

Step 3

like image 172
Dmytro Avatar answered Sep 21 '22 10:09

Dmytro