JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://knockoutjs.com/downloads/knockout-3.3.0.js"></script>
<div> <span>Control Label</span>
<input type="text" data-bind="validateText: ControlLabel, valueUpdate:'afterkeydown'" />
</div>
JavaScript
var arrValidKeys = [8, 16, 17, 20, 35, 36, 37, 39, 46];
ko.bindingHandlers.validateText = {
init: function (element, valueAccessor) {
$(element).on("keypress", 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);
// 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("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);
// 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);
// 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(valueAccessor()())) e.preventDefault();
});
}
};
var ViewModel = function () {
ControlLabel =...