mns
mns

Reputation: 683

Validating a textbox while typing special characters and having specific length

I have a textbox.I have to validate for special characters and max 15 characters in length. I have used below code for validating.

<input type="text" class="textFlag" onkeyup="ValidateFlagText(this)"/>


//function checks special character entry and total 15
//character checks
function ValidateFlagText(textBoxObj) {

     //skip events for space and control keys
    if (event.keyCode != 37 && event.keyCode != 39) {
        var originalValue = textBoxObj.value;
        var charCount = textBoxObj.value.length;

        if (!(!originalValue.match(/[_\W]/))) {
            alert("special characters not allowed");
            textBoxObj.value = originalValue.substring(0, charCount - 1);
        }

        if (charCount > 15) {
            alert("maximum 15 characters allowed");
            textBoxObj.value = originalValue.substring(0, charCount - 1);
        }

        textBoxObj.value = textBoxObj.value.substring(0, 15);
    }
}

One issue here is if i am holding and pressing. I have created a fiddle. http://jsfiddle.net/mnsscorp/QGRHP/6/

Thanks in advance.

Upvotes: 1

Views: 6240

Answers (3)

user3805935
user3805935

Reputation: 1

I used both onkeydown and onkeyup and the problem solved. Used like this:

<input type='text' id='titleNewColumn' onkeydown='ValidateFlagText(this)' onkeyup='ValidateFlagText(this)' />

Upvotes: 0

David Gilbertson
David Gilbertson

Reputation: 4853

As per this on MDN, 'auto repeat' (which is what happens when you hold down a key), fires the events: keydown, keypress, keydown, keypress... then finally a keyup.

If you want to check for length for each new character, then change your markup to listen to either keydown or keypress.

Upvotes: 1

Linga
Linga

Reputation: 10555

onKeyup should be:

<input type="text" class="textFlag" onkeydown="ValidateFlagText(this)"/>

onkeypress : invokes JavaScript code when a key is pressed

onkeydown : invokes JavaScript code when a key is held down (but not yet released)

onkeyup : invokes JavaScript code when a key is has been released after being pressed.

Upvotes: 1

Related Questions