简体   繁体   中英

How do I validate entry before input value is set?

I'm having a really strange problem. Here's my current Javascript:

jQuery('.highlightableTDCell input').keydown(function () {
    var val = jQuery(this).val();
    if (!GridView.prototype.validateStandardCellNumberFormat(val)) {
        return false;
    }
    else return true;
});

When I use this, I can still get away with entering an illegal character, but no more than that. I'm really confused because I thought this would happen first.

Inside of the keydown event, the element.value has not yet been updated to account for the key that is currently being pressed. If you want to stop the key from hitting the input box, you need to interrogate the event.which and see if it is a key you want to allow or not.

The event is raised before the new content entered the input (letting you cancel the default behavior.)

You can use something like this, to get the new content:

$('.highlightableTDCell input').keypress(function(e){
    var temp = this.value + String.fromCharCode(e.which)   

    return GridView.prototype.validateStandardCellNumberFormat(temp)
});

Note that it's not full proof. like when the user entered the new char in the middle of the input.

Validation should be done only on blur . With HTML5 it should be better, but not all browsers support it yet.

  • Tip: this.value == jQuery(this).val() There is no need to create jQuery object to get the value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM