Thursday, December 26, 2013

How to avoid user to enter a letter more than twice continuously


I have created a small example which will prevent user entering any character more than twice continously.


<!DOCTYPE html>
<html>
<script>
document.addEventListener('keypress', function(event) {
   var input = (document.getElementById("myInput").value);
    if(input.length > 1)
    {
        var enteredValue = String.fromCharCode(event.keyCode);
        var lastEnteredValue = input.substr(-1, 1);
        var lastBeforeValue = input.substr(-2, 1);

        if(enteredValue== lastEnteredValue && enteredValue == lastBeforeValue)
        {
          event.preventDefault();
        }
    }

}, true);
</script>
<body>
<input type = "text" id= "myInput">
</input>
</body>
</html>

The above example works perfectly if user enters two a's like "aa" and he will be blocked to enter another small "a". But he can still enter "A", which means we will allow "aaA".

To avoid even capital letters, you can add the below lines

       
var enteredValue = String.fromCharCode(event.keyCode).toLowerCase();
        var lastEnteredValue = input.substr(-1, 1).toLowerCase();
        var lastBeforeValue = input.substr(-2, 1).toLowerCase();

Fiddle for the same is here : http://jsfiddle.net/Vk65X/

No comments:

Post a Comment