Creating a Custom DataType Validation

I want to create my own validation class (I have many validation methods in JS that I want to translate into C # for use with MVC models) that work exactly the same as data annotations, checking on the client and server side: [DataType(MyDataType)]or as an attribute of DataAnnotation Validation, like this:[MyDataTypeValidation]

I don’t know which option is better for my “check” “check”

In the example, I have my FigurasDA class, and I want to do my own check for the nombre attribute.

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

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

, @"^[\w\s\.\-_]+$", , "Solo se permite letras, numeros y puntuaciones (- _.)", . ( "Alfanumerico" ).

, ?

+4
1

... ValidationAttribute IsValid. :

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(- _ .)" );
    }
}

:

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

, , Attributes MVC:

Step 1

Step 2

Step 3

+5

Source: https://habr.com/ru/post/1544521/


All Articles