I have to restrict length of a TextArea to 2 characters. I have found tons of answers. Reading those answers I have reached the following code. It has event handlers for 'keydown' and 'keyup'.
- Do you think this is correct and enough?
- Will it work in all major browsers?
http://jsfiddle.net/Lijo/VAYze/1/
- Note: I don’t need a error message to display. Hence regular expression validation will not be good option for me.
- Note: I am looking answer based on existing code – not a whole new answer
- Note: Key Codes are referred from http://www.asquare.net/javascript/tests/KeyCode.html and http://www.asquare.net/javascript/tests/KeyCode.html
UPDATE
To handle text dragged
into text area, I don't see a jQuery solution. I am planning to do a regular expression validator
with EnableClientScript
="false". It will validate in the server side only.This is to handle anything bypassed the existing jQuery operation. ASP Regular Expression Validator for Multi-line textbox
jQuery
$(document).ready(function () {
var maxLength = 2;
$('.multiline').keydown(function (e) {
var existingText = $(this).val();
var existingLength = existingText.length;
if (existingLength >= maxLength)
{
if (maxLength > 0)
{
if (!checkSpecialKeys(e))
{
$(this).val(existingText.substring(0, maxLength));
$(this).css('color','red');
//Newly entered character not rendered since false is returned
e.preventDefault();
}
}
}
});
//To trim the text if a paste happens
$('.multiline').keyup(function (e) {
var newText = $(this).val();
var newLength = newText.length;
if (newLength > maxLength) {
if (maxLength > 0) {
$(this).val(newText.substring(0, maxLength));
$(this).css('color','red');
}
}
});
}
);
function checkSpecialKeys(e)
{
if (e.keyCode >= 48 && e.keyCode <= 90)
{
return false;
}
if (e.keyCode >= 96 && e.keyCode <= 111)
{
return false;
}
else
{
return true;
}
}