If you are limiting characters based on maximum database field size, it gets a little more complicated.
What I have chosen to do is alert the user via JavaScript when they have exceeded the maximum character limit based on how much space each character requires in the database. I also require users of my app to have JavaScript enabled.
I'm not 100% certain I'm doing this completely right so if someone spots something please tag me.
function getUTF8Length(string)
{
var utf8length = 0;
for (var n = 0; n < string.length; n++)
{
var c = string.charCodeAt(n);
if (c < 128) utf8length++;
else if((c > 127) && (c < 2048)) utf8length = utf8length+2;
else utf8length = utf8length+3;
}
return utf8length;
}
The code that consumes the above function ...
// TEXTAREA INPUTS - ALERT WHEN MAX LENGTH EXCEEDED:
$(document).on('keyup', 'textarea', function(e)
{
var max_length = 65393;
var length = getUTF8Length(this.value);
var status_div = $(this).parent().find('div.status');
if (status_div)
{
$(this).parent().removeClass('error').removeClass('with_status');
$(status_div).removeClass('field_errors');
if (max_length == length)
{
$(this).parent().addClass('with_status');
$(status_div).html('<ul><li>Character limit reached.</li></ul>');
}
else if (max_length < length)
{
var percent = Math.floor(((length / max_length) * 100) - 100);
var percent_text = (percent > 1) ? ' by approximately ' + percent + '%' : ' by less than 1%';
$(this).parent().addClass('error').addClass('with_status');
$(status_div).addClass('field_errors');
$(status_div).html('<ul><li>Character limit exceeded' + percent_text + '.</li><li>Characters in excess of the limit will will not be stored.</li></ul>');
}
else
{
$(status_div).html('');
}
}
});