StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First - asp.net-mvc-3

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.

Related

MVC5 StringLength validation failing on int

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}")]

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.

Grails parent child form validation

I have an Invoice
class Invoice{
static hasMany = [lineItems: InvoiceItem]
double total
}
class InvoiceItem{
String description
double price
double qty
}
My issue is with form validation. If a user enters a string or invalid number format in either price or qty I get a
Failed to convert property value of type java.lang.String
to required type double for property price
BUT the error is in the Invoice object NOT in the LineItems object therefore I cannot highlight in RED the form appropriately. (And field value remains at zero when displayed so message is somewhat meaningless to user)
I was thinking of using COMMAND object with String parameters and validating their numeric value but I can't figure how to bind the InvoiceItem List.
What is the appropriate Grails way?
I could do all validation on the client side in javascript but that is not my question
You can do it with command objects. You need to read:
http://blog.peterdelahunty.com/2009/01/cool-way-to-dynamically-add-entries-to.html
command object data binding
Grails command object data binding
http://grails.1312388.n4.nabble.com/validating-nested-command-objects-td1346994.html

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.

How to persist reference data

After the every first start of my application I download all the necessary reference data (text file (csv format) with size of 1MB). This data contains about 30000 lines and each line is a data entry with name, latitude, longitude and height.
Whats the most performant way to save this data? I tried to store the list of these in the IsolatedStorageSettings. But this is absolutely the worst approach.
An other way to go is storing the text file in the IsolatedStorageFile directory and on each launching of the application loading the file and parse them to to my list.
The most inperformant part is reading the file. So I guess using a database like sqlite has the same issue, hasn't it?
How would you treat this issue?
Kind regards, Danny
I did something similar in WherOnEarth application. We have a SQLCE database that we store the data in and then load the stuff that is near by.
Background reading: http://www.silverlightshow.net/items/Windows-Phone-7.1-Local-SQL-Database.aspx & http://www.jeffblankenburg.com/2011/11/30/31-days-of-mango-day-30-local-database/
I have a sdf file that I ship with the app, a Data class shown below
[Table]
public class PointData : IPositionElement, INotifyPropertyChanged
{
[Column]
public string Description { get; set; }
[Column]
public double Latitude { get; set; }
[Column]
public double Longitude { get; set; }
Then we I read the points that are near by I get them with the following:
(from ht in _context.Points
where ht.Latitude >= bottomLeft.Latitude && ht.Latitude <= topRight.Latitude &&
ht.Longitude >= bottomLeft.Longitude && ht.Longitude <= topRight.Longitude
select ht
).ToArray();
This approach was fast enough for me (i.e. it took less time to get the items out of the sdf file than it did to position them on the screen an ddo all the other associated maths with that. Admitedly I wasnt trying to get 300000 items from the DB. There were more optimizations that I could have done in relation to indexing and things like that, but as I said it was quick enough at the moment so I will revisit it at some point later.

Resources