halera
halera

Reputation: 165

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?

Upvotes: 3

Views: 2880

Answers (3)

Felipe Castro
Felipe Castro

Reputation: 1613

I had the same issue recently, but since both the .Net code and Sql Server were considering one line break as two chars, I ended up changing the client side logic to also consider line breaks as two chars:

$('textarea[maxlength]').keyup(function () {
    var lineBreaks = $(this).val().split('\n').length - 1;
    var charsUsed = $(this).val().length + lineBreaks;
    if (charsUsed >= maxlength) {
        $(this).val($(this).val().substr(0, maxlength - lineBreaks));
        charsUsed = maxlength;
    }            
    var remaining = maxlength - charsUsed;
    $('#MyCounter').html("<strong>" + remaining + "</strong> characters remaining");
});

Upvotes: 0

Chris
Chris

Reputation: 117

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);
};

Upvotes: 2

Henry
Henry

Reputation: 1008

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) %>

Upvotes: 1

Related Questions