Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textarea and StringLength validator on server side count 'enter' as two characters

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?

like image 810
halera Avatar asked Feb 20 '26 12:02

halera


2 Answers

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);
};
like image 109
Chris Avatar answered Feb 23 '26 02:02

Chris


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) %>
like image 27
Henry Tshobo Avatar answered Feb 23 '26 01:02

Henry Tshobo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!