I have a curious problem with ASP.NET MVC3 client-side validation. I have the following class:
public class Instrument : BaseObject
{
public int Id { get
StringLength
works great, i used it this way:
[StringLength(25,MinimumLength=1,ErrorMessage="Sorry only 25 characters allowed for
ProductName")]
public string ProductName { get; set; }
or Just Use RegularExpression
without StringLength:
[RegularExpression(@"^[a-zA-Z0-9'@.\s]{1,25}$", ErrorMessage = "Reg Says Sorry only 25
characters allowed for ProductName")]
public string ProductName { get; set; }
but for me above methods gave error in display view, cause i had already ProductName field in database which had more than 25 characters
so finally i came across this and this post and tried to validate without model like this:
@Html.TextBoxFor(model => model.ProductName, new
{
@class = "form-control",
data_val = "true",
data_val_length = "Sorry only 25 characters allowed for ProductName",
data_val_length_max = "25",
data_val_length_min = "1"
})
@Html.ValidationMessageFor(model => model.ProductName)
this solved my issue, you can also do validation manually using jquery or using ModelState.AddModelError
hope helps someone.