Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validate textarea maxlength bug

I'm using jQuery.validate v 1.6.0 to validate my forms.

One of my database fields is limited to 1000 chars. I added a validation to the corresponding textarea like this:

In the header of my page, I add

$('form.validate').validate();

Inside my page, I declare:

<form method="post" class="validate" action="Save">
    <textarea name="description" minlength="15" maxlength="1000" id="description" class="required"></textarea>
    <input type="submit" value="Save">    
</form>

The issue I'm encountering is that jQuery seems to count the number of chars involved in a 'new line' differently as my database.

When I type exactly 1000 chars without new lines, all goes well, and the validation works. If I type 1000 chars with some new lines, jQuery allows the POST to happen, but my database refuses the insert/update, because the data is too big.

Any hints would be appreciated.

like image 526
grootjans Avatar asked Dec 03 '10 15:12

grootjans


1 Answers

I came a cross this perticular problem using jQuery Validate 1.9. Because I'm using ASP.NET MVC 3 and C# on the server line breaks was "\r\n" on the server but "\n" on the client. When I validated my textarea on the client the validation did not fail because "\n" is just counted as one character but when the text went to validation on the server where linebreaks are "\r\n" the validation would fail.

My soultion to this problem was to override jQuery validation method "rangelengt" because i also have a minimum length defined:

$.validator.addMethod('rangelength', function (value, element) {
        var maxlen = parseInt($(element).attr('data-val-length-max'));
        if (maxlen > 0) {
            var remaining = (maxlen - (parseInt($(element).val().replace(/(\r\n|\n|\r)/gm, '\r\n').length)));
            if (remaining < 0) {
                return false;
            }
        }

        return true;
    });

So what this code actually does is to get the maxlength value and then get the value from the element and then it replaces all "\n" characters with "\r\n" to get the same count of characters as the server would.

like image 162
Robin Ridderholt Avatar answered Nov 15 '22 07:11

Robin Ridderholt