I have this Knockout custom binding to validate a text box to contain only English letters. But, it seems like Javascript's String.fromCharCode
returns wrong values.
For example, the Hebrew letter "ש" returns as the English letter "A", and the number "1" from the right numbers pad has returns as "a"...
Here is my Knockout binding:
var arrValidKeys = [8, 16, 17, 20, 35, 36, 37, 39, 46];
ko.bindingHandlers.validateText = {
init: function (element, valueAccessor) {
$(element).on("keydown", function (event) {
//Regex pattern: allow only (A to Z uppercase, a to z lowercase)
var englishAlphabet = /[A-Za-z]/g;
// Retrieving the key from the char code passed in event.which
var key = String.fromCharCode(event.which);
// keyCodes list: http://stackoverflow.com/a/3781360/114029
// check that the key is valid with the above Regex
valueAccessor()($(this).val());
return ((jQuery.inArray(event.keyCode, arrValidKeys) != -1) || englishAlphabet.test(key));
});
$(element).on("keyup", function (event) {
//Regex pattern: allow only (A to Z uppercase, a to z lowercase)
var englishAlphabet = /[A-Za-z]/g;
// Retrieving the key from the char code passed in event.which
var key = String.fromCharCode(event.which);
// keyCodes list: http://stackoverflow.com/a/3781360/114029
// check that the key is valid with the above Regex
valueAccessor()($(this).val());
return ((jQuery.inArray(event.keyCode, arrValidKeys) != -1) || englishAlphabet.test(key));
});
$(element).on("paste", function (e) {
var englishAlphabet = /[A-Za-z]/g;
if (englishAlphabet.test($(this).val()))
valueAccessor()($(this).val());
else
e.preventDefault();
});
}
};