Validate Year

Allow only delete, backspace,left arrow,right arrow, Tab and numbers on an input.

by nwellcome

HTML

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <meta name="description" content="">
        <meta name="author" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div id="container">
            <header></header>
            <div id="main" role="main">
                Input a 4-digit year: <input type="text" class="validateYearTextBox" />
            </div>
            <footer></footer>
        </div> 
    </body>
</html>

JavaScript

function checkValidInput() {
    // Allow only delete, backspace, left arrow, right arrow, 
    // Tab, ctrl+v and numbers
    $(".validateYearTextBox").keydown(function(event) {
        if (!((event.keyCode == 46 || 
            event.keyCode == 8  || 
            event.keyCode == 37 || 
            event.keyCode == 39 || 
            event.keyCode == 9) || 
            (event.ctrlKey && event.keyCode == 86) ||  
            $(this).val().length < 4 &&
            ((event.keyCode >= 48 && event.keyCode <= 57) ||
            (event.keyCode >= 96 && event.keyCode <= 105)))) {
            // Stop the event
            event.preventDefault();
            return false;
        }
    });
    
    // This removes non-numeric characters and truncates the length
    // to 4 if the user copy + pasted.
    $(".validateYearTextBox").keyup(function(event) {
        var value =  $(this).val();
        value = value.replace(/[^0-9]/,'');
        value = value.substr(0,4);
        $(this).val(value);
        console.log(value);
    });
}


$(document).ready(function() {
    checkValidInput();
});