Validation with Dataannotation

Asked

Viewed 99 times

2

I want to do a validation with the size of a field of the type int using Dataannotation, I used [MaxLengthAttribute(10)], only at the moment that I will make the View Index to bring up the list of entries, returns an error.

This is my code:

[Display(Name = "RE")]
[Required(ErrorMessage = "informe o RE")]
[MaxLengthAttribute(10)]
public int usuRE { get; set; }

This is the mistake:

"There was an error running the select code Retrieve Metadata for 'Loginuser.Models.Usuario'. The Property 'usere' is not a String or Byte array. Length can only be configured for String and Byte array properties.'"

Is there any other way I can validate the size of this field using Dataannotation? A colleague said I could take the [MaxLengthAttribute(10)] to HTML and do that validation there, but I don’t know how to do that, someone could help me?

  • Hello @Rafael. Put your structured code on your question instead of posting images. The same for the error message.

  • 1

    Okay, you can leave it, next time I’ll do it, sorry!

  • You can do it now! Edit your question and enter the code :)

2 answers

5

A Dataannotation Maxlengthattribute is used to limit string size.

To set a range of values for integer properties, you must use Dataannotation Range, as below:

[Range(18,65)]
public int Idade { get; set; }

2


In your case the MaxLengthAttribute will not work because, as the error itself indicates, it only applies to types String or array of Byte.

There are two ways around the problem:

1. Instead of using the type int, move on to string and then use the [MaxLengthAttribute(10)], but there may have unintended implications on the database:

[Display(Name = "RE")]
[Required(ErrorMessage = "informe o RE")]
[MaxLengthAttribute(10)]
public string usuRE { get; set; }

2. If the objective is to allow 0 to 9.999.999.999 (size = 10), then you will have to change the type to long, as the maximum of the int is 2.147.483.647:

[Display(Name = "RE")]
[Required(ErrorMessage = "informe o RE")]
[Range(0, 9999999999)]
public long usuRE { get; set; }
  • But what if I want the user to enter a RE with at least 4 digits? I need the RE to have at least 4 digits and at most 10

  • 1

    Then just change the range to (1000, 9999999), since the minimum number of 4 digits is 1000.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.