Why does not the data annotation StringLength [] and MaxValuie [] work for me?

1

I am having problems to implement the asp.net mvc 5 annotations. When designing my model, I put the [StringLength] annotation to validate that the user enters a minimum and maximum number of digits. It works well, but at the moment of making the post, I never get to the controller and when I review the response, a conversion error appears. The following is the exception.

  

Unable to convert an object of type 'System.Int32' to type 'System.String'

My model:

public class LoginViewModel
{
    [Required]
    [StringLength(8, MinimumLength = 7, ErrorMessage = "mi error")]
    [Display(Name = "Rut")]
    public int UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Multiclave")]
    public int Password { get; set; }
}

Try with MaxValue[] but I got the same problem. With another type of error, but based on the data conversion.

Could someone help me please?

    
asked by vcasas 28.05.2018 в 18:07
source

1 answer

3

StringLength, as the name implies, works for data of type string, and you are using it in a property of type int.

In fact, why does something called "UserName" declare it as int? the same for Password.

Validate numbers only try something like this:

public class LoginViewModel
{
    [Required]
    [StringLength(8, MinimumLength = 7, ErrorMessage = "mi error")]
    [RegularExpression("^[0-9]*$")] // <-- expresión regular
    [Display(Name = "Rut")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [RegularExpression("^[0-9]*$")]  // <-- expresión regular
    [Display(Name = "Multiclave")]
    public string Password { get; set; }
}
    
answered by 28.05.2018 / 18:14
source