Ismael
Ismael

Reputation: 2340

How to avoid non valid input in text field with javascript events?

I cannot handle properly some events in input type="text". I just need a filter to only accept [^0-9] chars.

I need the following help:

What i tried so far:

What i want:

From all problems above, i can handle nicely or weirdly (aka: keuup) the input, but Right Click + Paste (mouse) NEVER trigger ANY EVENT so i can do the properly treatment.

I thought about doing Interval Check, but this is too ugly.

EDIT:

Code below

function soNumeroInteiro_keypressHandler(event)
{
    var code = event.keyCode || event.which;

    switch(code)
    {
        case  8: // backspace
        case 37: // left
        case 39: // right
        case  9: // tab
        case 46: // delete
        case 35: // end
        case 36: // home
            return true;
        break; 

        case  86: // control + A
        case  97: // control + V
        case 120: // control + X
            if (event.ctrlKey) {
                return true;                
            }
        break;
    }

    var tecla = String.fromCharCode(code);

    return tecla.match(/^\d$/) != null;
}

function soNumeroInteiro_keyupHandler(event)
{
    event.currentTarget.value = event.currentTarget.value.replace(/[^0-9]/g, '');
}

Upvotes: 2

Views: 498

Answers (1)

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

Please see this question for the mouse click events: How to distinguish between left and right mouse click with jQuery

NOW you have the mouse click event, even the right click, you can then poll the content for a short bit (2 seconds?) to detect changes and handle the content validation. This way, you COULD choose to either accept valid or reject the content based on your business logic needs.

EDIT: Just to add a note, the onpaste event will not work correctly in that it will fire (in some test cases at least) prior to the content being pasted.

Example:

$('#pasteyMe').on('paste', function() {
    $(this).val();// gets the content prior to the paste event
});

To work around this, you could set another event watcher such as change and then fire that:

$('#pasteyMe').on('click focus blur paste', function() {
    var me = this;
    window.setTimeout(function() {
       $(me).trigger('change');
    }, 1);
});

$('#pasteyMe').change(function() {
    $('#resulty').text($(this).val());
});

See this in action here: http://jsfiddle.net/MarkSchultheiss/kQxAj/

Upvotes: 1

Related Questions