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
You can check a couple different properties of the event to see which key(s) were pressed:
event.whichevent.shiftKeyevent.ctrlKeyYou can then combine that information with the current value to determine the new value. It gets complicated when you need to handle
keypressevents 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.