We try to add real-time input validation for dynamic element with some regex. Let say, user allowed only to type “numeric” and disallow any others alphabet and symbols.
Then, we can write a small plugin, at this example, i use https://github.com/akzhan/jquery-keyfilter for Regex validation.
Then, we just need to write this simple and easy plugin :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | (function($) { $.fn.validNumber = function(selector) { /** * Attach key filter with regex int only for dynamic element */ $(document).on(‘click’, selector, function() { $(this).keyfilter(/[\dA-F]/); }); /** * When input have more than 1 digit but leading with 0 * Remove the leading zero */ $(document).on(‘keyup’, selector, function() { if($(this).val().length > 1 && $(this).val()[0] == "0") { $(this).val($(this).val().substring(1)); } }); }; })(jQuery); |
Then, we just need to use this libraries by :
1 | $(document).validNumber(‘input’); |