views:

15

answers:

1

I want to create different inputmasks like Date Input mask in Javascript. What will be the best way to create masks. (Without any Framework!)

Thanks

+1  A: 

Attach an event listener to the onKeyDown handler on your input. Something like this:

function numericOnly( e )
{

if( !e ) e = event;
var kc = e.which || e.keyCode;
var shift = e.shiftKey;

// Numeric and decimal point only
return( kc == 8 || kc == 9 || kc == 46 ||     // Backspace, tab, delete
        kc == 37 || kc == 39 ||               // Left and right arrow keys
        kc == 110 || kc == 190 ||             // Decimal point (keyboard and num pad)
      ( kc >= 48 && kc <= 57 && !shift ) ||   // Digits above letter (no shift)
      ( kc >= 96 && kc <= 105 ) );            // Digits on num pad
}

For date validation you would also include the / character. Then I would attach an event handler to the onBlur event on your inputs. Use that even handler to run the input against a regex to make sure a proper date was entered.

<input onkeydown="JavaScript: numericOnly( e );"
       onblur="JavaScript: checkDate( this.value );">
Sparafusile