0

I am trying to perform validation on some fields by binding a function to the keypress event.

I make several custom validation objects and place them in an array validations (full code not shown):

    {"id": "DE-mname", "events":"keypress", "func": function(obj){
        return validator.name($(obj).val()) || $(obj).isEmpty();
    }

and attach it to certain components using the following method and a custom jquery plugin:

DataEntry.prototype.attachValidators = function(){
        var x, validation;
        for(x in this.validations)
        {
            validation = this.validations[x];
            $("#" + validation.id).attachValidation(validation.events,validation.func); 
        }
};

/**
 *
 * @param {String} Events - a string of events you want validation to execute on
 * should be delimited by a space.
 * @param (Function) validateFunc - a function used to determine if the field is valid,
 * must return true, truthy, false or falsey values, the function may accept an object
 * as the first parameter which will be the selected jquery object.
 */
(function($){
    $.fn.extend({
        attachValidation: function(events, validateFunc){
            events += " validate";
            return this.each(function(){
                var that = this;
                $(this).bind(events, function(event){
                    if (validateFunc(that, event)) {
                        $(that).removeClass("error");
                    }
                    else {
                        $(that).addClass("error");
                    }
                    jq(this).trigger("errorAttached");
                });
            });
        }
    });
})(jQuery

The problem I am experiencing is that when the keypress event is fired and the validation function checks the .val() of a textbox component, the new value does not contain the current key being pressed.

For example: If I clicked in an input field and hit the '$' key, $(obj).val()) would return an empty string, instead of $. I would like to retrieve the value with the key currently being pressed. Please note that I cannot switch to the keyup event

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • Ok, working on switching to checking for the tab key, after this is working I have the harder task of figuring out who to give credit for the answer – Kevin Bowersox Jul 11 '11 at 11:41

4 Answers4

2

You can check a couple different properties of the event to see which key(s) were pressed:

You can then combine that information with the current value to determine the new value. It gets complicated when you need to handle keypress events like Delete, Backspace, Delete, Ctrl-C, Ctrl-V, etc.

In general, your task will be much easier if you switch to using keyup. I know you said you can't, but I'm just putting that out there.

One other point: there is no jQuery .isEmpty() method, as in your code.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • I agree, however when I use the keyup event the field validates if I tab to it, causing it to receive the error class that makes the field red. BTW, isEmpty() is my own custom plugin. – Kevin Bowersox Jul 11 '11 at 11:35
  • 2
    You'll have a much easier time with validation if you just use `keyup` and work around the tab issue. Another thought: **just use the `.change()` event**. – Matt Ball Jul 11 '11 at 11:37
  • the change event only fires on blur, which makes the validation seem less responsive – Kevin Bowersox Jul 11 '11 at 11:39
  • In the keypress event, the `shiftKey` and `ctrlKey` properties are irrelevant, since the `which` property already corresponds to a character code rather than a key code. – Tim Down Jul 11 '11 at 13:54
1

Try to use the charCode conversion to obtain the pressed button

String.fromCharCode(e.which)

take a look at the fiddle

http://jsfiddle.net/5ASA9/3/

You cannot check directly the val of your input because this event occurs before the field valorization.

VAShhh
  • 3,494
  • 2
  • 24
  • 37
1

the keypress event is probably a poor choice to use for validation of this type as it occurs before the change event of the target object (the textbox in this case). You can capture the the key character being entered, but since the textbox value has not yet been changed you can not validate the new value. Perhaps keyup would be a better choice for you. Which you say you can not use, why? What prevents you from using this event?

Cos Callis
  • 5,051
  • 3
  • 30
  • 57
0

Use the HTML5 input event. See this answer.

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536