StringLength works fine, I used it like this:
[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 the above methods gave an error in the display view because I already had a ProductName field in the database that had more than 25 characters
so finally I came across this and this and tried to check without a model :
<div class="editor-field"> @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" }) <span class="validation"> @Html.ValidationMessageFor(model => model.ProductName)</span> </div>
this solved my problem, you can also do the check manually using jquery or using ModelState.AddModelError
Hope helps someone.
stom May 03 '15 at 11:58 a.m. 2015-03-03 11:58
source share