Setting MaxLength gives you error - asp.net-mvc

Following is one of the property in my MVC model.
[Display(Name = "Event ID")]
[MaxLength(8, ErrorMessage = "Event ID can be of maximum 8 characters long")]
[Required(ErrorMessage="Event ID must be entered")]
public Nullable<int> ID_EVENTO { get; set; }
I have bound the model with a View, and when I try to click "Submit" button, it gives following runtime error -
Unable to cast object of type 'System.Int32' to type 'System.Array'
While, if I remove the "MaxLength" attribute, it starts working.
What could be the issue here?

MaxLength is used to specify the maximum length of array or string data allowed in a property.
Your ID_EVENTO is a nullable int (rather than array or string), that's why the attribute doesn't work. Sounds like you either want to remove the attribute or use a different one - Range or something?

Related

Variable of type Long is required

I have one ViewModel that has property Id of type long without attribute [required]. This model I use for search.
Problem : Why always when i try to make search request and input for property Id leave empty i get validation error as Id field is required ?
Make your model property nullable.
public long? myprop { get; set; }

MVC 5 - change Data anotation error message for Integers

In my Mvc5 test project I have a model with a property like the following:
[Required]
[DisplayName("Codigo Cliente")]
public int ClientCode{ get; set; }
the default error message when the user enteres a letter of special character in the editor is:
The field Codigo Cliente must be a number.
How can I modify this? in this case I need to change the language, but in case that I wanted to show a more specific error what can I do?
I have tried with the DataType attribute but the Enum does not have a value that applys for this case (numbers)
Use Range:
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.rangeattribute.aspx
Or use IntegerOnly from Data Annotations Extensions
http://dataannotationsextensions.org/Integer/Create
The simplest way I found to solve this issue is use String with Range attribute in Data Annotation Model like specify below.
[Required]
[Range(0, int.MaxValue, ErrorMessage = "Codigo Cliente must be a positive or negative non-decimal number.")]
[DisplayName("Codigo Cliente")]
public string ClientCode { get; set; }
In Range attribute you can specify your custom Error Message.
For Interger use int.MaxValue , For double use double.MaxValue like so on.
I hope this will help you a lot.
If you want to specify a message you must use this
[Required(ErrorMessage = "your message")]
If you want to use a lang. based message is not that easy. You can use multiple resource file (for every language you need) and try a custom error binder that extends the DefaultModelBinder and make an override of the method BindModel(), there you can make your custom validation ad use your custom language message.

How can I change the error message for implicitly required properties in a view model?

I have properties declared in my view model like:
[Required(ErrorMessage = "The Date field is required for Start.")]
[Display(Name = "Start")]
public DateTime DateStart { get; set; }
However, I am still getting a default The Start field is required error message. I assume this is because a non-nullable DateTime is implicitly required, and the Required attribute is ignored. Is there a way to customise my error message for these specific properties, besides making them nullable?
You right, your problem is that your property is not nullable. For not nullable properties attribute Required is meaningless. When there is no StartDate value, validation is not go to your Required attribute and fails on previous step. If you want to get your ErrorMessage you should
use:
[Required(ErrorMessage = "The Date field is required for Start.")]
[Display(Name = "Start")]
public DateTime? DateStart { get; set; }
You cannot customize ErrorMessage for nonullable types that get null on modelbinding, cause it is hardcoded deep in MVC framework.
I've started with refresh new test project in MVC 4 and create a test model
public class TestModel {
[Required(ErrorMessage = "The Date field is required for Start.")]
[Display(Name = "Start")]
public DateTime DateStart { get; set; }
}
Then in my model I just have this:
#using(Html.BeginForm()){
#Html.ValidationMessageFor(a => a.DateStart);
#Html.TextBoxFor(a => a.DateStart)
<input type="submit" value="add"/>
}
When I remove clean the text box and hit submit, I am getting the customized error message instead of the default.
The Date field is required for Start.
This make sense to me, imagine if this is a multilingual application, you will definitely need to customize the error message for that country. It doesn't take a rocket scientist to realise the need for customized message. And I would expect MVC team have that covered.

Change the default error message for data type in mvc3

I'm developing in mvc 3 and have a little question.
I want to change the default error message for invalid data type.
let say I've a model with the prop Price, and I want his error message for input "aaa" will be "The only value you can enter here is a number".
what is the easiest way of doing that?
(I want to do it for all of my models)
You could use a Regular Expression data annotation on your model property, e.g.:
[RegularExpression(#"^[0-9\.]*$", ErrorMessage="The only value you can enter here is a number")]
public double Price { get; set; }
You should approach validation from a white list point of view - i.e. what should be allowed through, as opposed to a black list, which would be what is invalid.
More information here:
http://www.asp.net/mvc/tutorials/mvc-music-store-part-6
Hope this helps!
Sam
http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx
Assuming that you are working with entity framework or Linq to SQL and your class name is Product. here is the example for that. create a partial class like below;
[MetadataType(typeof(Product.MetaData))]
public partial class Product {
private class MetaData {
[Required(ErrorMessage = "The only value you can enter here is a number")]
public decimal Price { get; set; }
}
}
you should add the following using statement in order to use dataanotations for validation;
using System.ComponentModel.DataAnnotations;

How can I specify the order of DataAnnotation ValidationAttribute's?

The question here is similar, but I don't have any domain object inheritance. My field and validation tags are in the following order, but the MustBe18 error and the Required error are the only ones that print. I have several other fields in this model with much more validation, but the order of ValidationAttribute's in the code doesn't seem to matter. jfar's answer in the linked post seems to suggest a helper could be built, but how? How can the order be controlled?
[Required(ErrorMessage = "This field is required")]
[DisplayName("Date of Birth")]
[MustBeValidDate(ErrorMessage = "Must be a valid date")]
[MustBe18(ErrorMessage = "You must be 18 years old")]
[MustNotBeOver100(ErrorMessage = "This caller is too old")]
public string dob { get; set; }
MustBe18 : ValidationAttribute (the overloaded IsValid method)
try
{
DateTime dob = new DateTime(DateTime.Now.AddYears(-18).Year, DateTime.Now.Month, DateTime.Now.Day);
return DateTime.Compare(DateTime.Parse(value.ToString()), dob) <= 0;
}
catch
{
return false;
}
The only way to specify the order is to create your own ModelValidatorProvider which can then order the attributes. This will probably be tricky because you'd also need to create overloads for each attribute that takes an Order parameter ( don't know if they already do ).
If all you mind is the order in which validation summaries appear all you'd need to do is loop through the ModelState entries and spit out the errors from there.

Resources