I have a StringLength validator on textarea
[StringLength(10, ErrorMessage = "The {0} must be {1} characters or less")]
So when I press enter and then type 9 characters, the client validation does not display any errors; but if I submit the form, server validation says that there is more than 10 characters.
So on client side enter means one character and on server, two. It is not the same behavior.
Probably I would need to implement my own validator which would do it, right?
Or is there any validators I may use instead of StringLength, to validate textarea content length correctly?
See my answer here: New line characters in text area increases text length in C#
You can change the default behavior for getLength to double count newlines by adding the following to your JS somewhere.
$.validator.prototype._getLength = $.validator.prototype.getLength;
$.validator.prototype.getLength = function (value, element) {
// Double count newlines in a textarea because they'll be turned into \r\n by the server.
if (element.nodeName.toLowerCase() === 'textarea')
return value.length + value.split('\n').length - 1;
return this._getLength(value, element);
};
Add attribute to your property
[RegularExpression(@"^[\s\S]{0,10}$",ErrorMessage="maximun length must be 10")]
then in your view
<%: Html.ValidationMessageFor(m => m.MyText) %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With