MVC5 StringLength validation failing on int - validation

i have the following validations specified for an int field.
[Required(ErrorMessage = ValidationMessages.ResponseRequired)]
[Digits(ErrorMessage = ValidationMessages.DigitsOnly)]
[StringLength(6, MinimumLength = 6, ErrorMessage = ValidationMessages.InvalidLength)]
public int? Code { get; set; }
When i take out the StringLength then the post is successful. With it, i get 500 exception:
Unable to cast object of type 'System.Int32' to type 'System.String'
What is going on here? Do i need to write a custom one for int? In this case, i just want to make sure that the user is entering 6 digits.

String length isnt really valid for an int, though?
What is it that you are trying to achieve? That the input is greater than 99,999?
Then you can use:
[Range(100000,int.MaxValue)]

You can use Range or RegularExpression for control your digits length.
Range[0,999999]
Range[100000,999999]
[RegularExpression(#"\d{6}")]

Related

Need to modify type of field for protobuf

I have quick question for modifying type of field for protobuf.
I have create the int64 id something like below.
message test {
int64 id = 1;
}
And I find out I can not set this id as null because of the type.
Therefore, I would like to modify it from int64 to int64value but do not sure is there any standard way for this kind of operation.
message test {
// int64 id = 1;
int64value id = 2;
}
or
message test {
int64 id = 1 [deprecated=true];
int64value id = 2;
}
Thanks and open to any kind of input!
I would like to get more standard way for this kind of operation.
You can reference values by field number or by name. So your first approach works. As long as you do not need backwards compatibility you could just change the id from int to your id type. This would result in a cleaner code.
For the use of the deprecated Attribut you could check out this:
Google protobuf 3: deprecated a field, but cannot remove the dependencies?

Replace field with same type, but different meaning in Protocol Buffers

I'd like to update a message in Protocol Buffers:
message Person {
string name = 1;
}
Now, suppose that I don't want a name for a Person, but only its address:
message Person {
string address = 1;
}
Now, the id could remain 1 since the type is always a string, but I was wondering if it's better to rewrite the message in this way:
message Person {
string address = 2;
reserved 1;
}
in order to have more readability between versions.
you can just change the field name safely(if you want to keep same id and same type), please check below post would help you.
Protocol buffer: does changing field name break the message?
and also in my opion it is always good have
required or optional
annotation to the message fields

grails integer field default validation

I have a grails domain class that looks like:
class Person {
String name
int age
}
When I show the default "create" view (using scaffolding), the age field shows as a required field (with an asterisk next to it). Is there a way to make it show up as non-required and default to blank?
I've tried adding
constraints = {
age blank:true, nullable:true
}
This results in the field being allowed to be empty but it still shows up with the asterisk next to it.
An int is a primitive type and cannot be blank. You would have to change it to an Integer, then a null value would mean that it's blank.

MVC3 Range validation when value is larger then zero

I have a product order page where the minimum order is 2500. I want to use the Range annotation validation in the model to validate this, but I also need the user to be able to select 0 of this product if they don't want any.
Now I use:
[Display(Name = "Item1")]
[Range(1000, int.MaxValue, ErrorMessage = "You need to order minimum {1} of Item1")]
public int OrderedItem1{ get; set; }
Is there an easy way to accomplish this without creating a custom validator?
Yes, you could use the regular expression validation attribute.
[RegularExpression(#"SomeRegExpression", ErrorMessage = "Min order error")]
I found out that I could do this using this regular expression validation attribute:
[RegularExpression(#"^(?:0|\d{5,}|[1-9]\d\d\d)$", ErrorMessage = "You need to order minimum 1000 of Item1")]
Thanks to Ryand Johnson for helping out.

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

What is the difference in behavior of [MaxLength] and [StringLength] attributes?
As far as I can tell (with the exception that [MaxLength] can validate the maximum length of an array) these are identical and somewhat redundant?
MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.
From MSDN:
Specifies the maximum length of array
or string data allowed in a property.
StringLength is a data annotation that will be used for validation of user input.
From MSDN:
Specifies the minimum and maximum
length of characters that are allowed
in a data field.
Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):
The validation messages associated with these attributes will actually replace placeholders associated with the attributes. For example:
[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }
Will output the following if it is over the character limit:
"Address can have a max of 100 characters"
The placeholders I am aware of are:
{0} = Property Name
{1} = Max Length
{2} = Min Length
Much thanks to bloudraak for initially pointing this out.
Following are the results when we use both [MaxLength] and [StringLength] attributes, in EF code first. If both are used, [MaxLength] wins the race. See the test result in studentname column in below class
public class Student
{
public Student () {}
[Key]
[Column(Order=1)]
public int StudentKey { get; set; }
//[MaxLength(50),StringLength(60)] //studentname column will be nvarchar(50)
//[StringLength(60)] //studentname column will be nvarchar(60)
[MaxLength(50)] //studentname column will be nvarchar(50)
public string StudentName { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
All good answers...From the validation perspective, I also noticed that MaxLength gets validated at the server side only, while StringLength gets validated at client side too.
One another point to note down is in MaxLength attribute you can only provide max required range not a min required range.
While in StringLength you can provide both.
MaxLengthAttribute means Max. length of array or string data allowed
StringLengthAttribute means Min. and max. length of characters that are allowed in a data field
Visit http://joeylicc.wordpress.com/2013/06/20/asp-net-mvc-model-validation-using-data-annotations/
You can use :
[StringLength(8, ErrorMessage = "{0} length must be between {2} and {1}.", MinimumLength = 6)]
public string Address { get; set; }
The error message created by the preceding code would be "Address length must be between 6 and 8.".
MSDN: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-5.0
I have resolved it by adding below line in my context:
modelBuilder.Entity<YourObject>().Property(e => e.YourColumn).HasMaxLength(4000);
Somehow, [MaxLength] didn't work for me.
When using the attribute to restrict the maximum input length for text from a form on a webpage, the StringLength seems to generate the maxlength html attribute (at least in my test with MVC 5). The one to choose then depnds on how you want to alert the user that this is the maximum text length. With the stringlength attribute, the user will simply not be able to type beyond the allowed length. The maxlength attribute doesn't add this html attribute, instead it generates data validation attributes, meaning the user can type beyond the indicated length and that preventing longer input depends on the validation in javascript when he moves to the next field or clicks submit (or if javascript is disabled, server side validation). In this case the user can be notified of the restriction by an error message.

Resources