// Restricts input for the set of matched elements to the given inputFilter function.(function($) {$.fn.inputFilter = function(callback, errMsg) {return this.on("input keydown keyup mousedown mouseup select contextmenu drop focusout", function(e) {if (callback(this.value)) {// Accepted valueif (["keydown","mousedown","focusout"].indexOf(e.type) >= 0){$(this).removeClass("input-error");this.setCustomValidity("");}this.oldValue = this.value;this.oldSelectionStart = this.selectionStart;this.oldSelectionEnd = this.selectionEnd;} else if (this.hasOwnProperty("oldValue")) {// Rejected value - restore the previous one$(this).addClass("input-error");this.setCustomValidity(errMsg);this.reportValidity();this.value = this.oldValue;this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);} else {// Rejected value - nothing to restorethis.value = "";}});};}(jQuery));
您现在可以使用inputFilter插件安装输入过滤器:
$(document).ready(function() {$("#myTextBox").inputFilter(function(value) {return /^\d*$/.test(value); // Allow digits only, using a RegExp},"Only digits allowed");});
$(document).ready(function() {$("#txtboxToFilter").keydown(function(event) {// Allow only backspace and deleteif ( event.keyCode == 46 || event.keyCode == 8 ) {// let it happen, don't do anything}else {// Ensure that it is a number and stop the keypressif (event.keyCode < 48 || event.keyCode > 57 ) {event.preventDefault();}}});});
// Allow only backspace and deleteif (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) {// let it happen, don't do anything}else {// Ensure that it is a number and stop the keypressif ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) {
}else {event.preventDefault();}}
$(document).ready(function() {$("#formID").validate({rules: {field_name: {numericOnly:true}}});});
$.validator.addMethod('numericOnly', function (value) {return /^[0-9]+$/.test(value);}, 'Please only enter numeric values (0-9)');
/*** @author Tom Van Schoor* @company Tutuka Software*/(function($) {/*** @param {Object}* $$options options to override settings*/jQuery.fn.inputmask = function($$options) {var $settings = $.extend( {}, $.fn.inputmask.defaults, $$options);
return this.each(function() {// $this is an instance of the element you call the plug-in onvar $this = $(this);
/** This plug-in does not depend on the metadata plug-in, but if this* plug-in detects the existence of the metadata plug-in it will* override options with the metadata provided by that plug-in. Look at* the metadata plug-in for more information.*/// o will contain your defaults, overruled by $$options,// overruled by the meta-datavar o = $.metadata ? $.extend( {}, $settings, $this.metadata()) : $settings;
/** if digits is in the array 'validators' provided by the options,* stack this event handler*/if($.inArray('digits', o.validators) != -1) {$this.keyup(function(e) {$this.val(stripAlphaChars($this.val()));});}
/** There is no such things as public methods in jQuery plug-ins since* there is no console to perform commands from a client side point of* view. Typically only private methods will be fired by registered* events as on-click, on-drag, etc... Those registered events could be* seen as public methods.*/
// private methodvar stripAlphaChars = function(string) {var str = new String(string);str = str.replace(/[^0-9]/g, '');return str;}
});};
// static public functions//jQuery.fn.inputmask.doSomething = function(attr) {
//};
// static public members//jQuery.fn.inputmask.someStaticPublicMember;
// some default settings that can be overridden by either $$options or// metadata// If you need callback functions for the plug-in, this is where they get// setjQuery.fn.inputmask.defaults = {validators : []};})(jQuery);
jQuery.validator.addMethod("numberOnly", function (value, element) {var result = !isNaN(value);return this.optional(element) || result;}, jQuery.format("Please enter a valid number."));
$("#txtboxToFilter").keydown(function(event) {// Allow only backspace and deleteif ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 ) {// let it happen, don't do anything}else {// Ensure that it is a number and stop the keypressif ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {event.preventDefault();}}});
$(document).ready(function(){$("#textBoxId").bind("change",checkInput);});
function checkInput(){// check if $('#textBoxId').val() is under your constraints// then change its value, removing the last character// since this event will be called each time you// type a character}
$("input.inputPhone").keyup(function() {var jThis=$(this);var notNumber=new RegExp("[^0-9]","g");var val=jThis.val();
//Math before replacing to prevent losing keyboard selectionif(val.match(notNumber)){ jThis.val(val.replace(notNumber,"")); }}).keyup(); //Trigger on page load to sanitize values set by server
var checknumber = $('#textbox_id').val();
if(jQuery.isNumeric(checknumber) == false){alert('Please enter numeric value');$('#special_price').focus();return;}
$(this).on( 'keypress', function( e ){// Ensure that it is a number and stop the keypressif (e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) {e.preventDefault();}});
//Event of data being keyed in to textbox with class="numericField".$(".numericField").keyup(function() {// Get the non Numeric char that was eneteredvar nonNumericChars = $(this).val().replace(/[0-9]/g, '');// Now set the value in text box$(this).val( $(this).val().replace(nonNumericChars, ''));
});
function validate_profile(frmid) {var form = $('#' + frmid);var error = $('.alert-danger', form);var success = $('.alert-success', form);form.validate({errorElement: 'span', //default input error message containererrorClass: 'help-block', // default input error message classfocusInvalid: true, // do not focus the last invalid inputignore: "",rules: {contact_no: {required: true,minlength: 10,maxlength: 10,number: true}, email_id: {required: true,email: true}},invalidHandler: function (event, validator) { //display error alert on form submitsuccess.hide();error.show();Metronic.scrollTo(error, -7000);},highlight: function (element) { // hightlight error inputs$(element).closest('.form-group').addClass('has-error'); // un set error class to the control group$(element).closest('.form-group').removeClass('has-success'); // set success class to the control group},unhighlight: function (element) { // revert the change done by hightlight$(element).closest('.form-group').removeClass('has-error'); // un set error class to the control group$(element).closest('.form-group').addClass('has-success'); // set success class to the control grouperror.hide();},success: function (label) {label.closest('.form-group').removeClass('has-error');label.closest('.form-group').addClass('has-success');},submitHandler: function (form) {success.show();error.hide();form.submit();}});}
$('input[name="number"]').keyup(function(e) {var float = parseFloat($(this).attr('data-float'));
/* 2 regexp for validating integer and float inputs *****> integer_regexp : allow numbers, but do not allow leading zeros> float_regexp : allow numbers + only one dot sign (and only in the middle of the string), but do not allow leading zeros in the integer part*************************************************************************/var integer_regexp = (/[^0-9]|^0+(?!$)/g);var float_regexp = (/[^0-9\.]|^\.+(?!$)|^0+(?=[0-9]+)|\.(?=\.|.+\.)/g);
var regexp = (float % 1 === 0) ? integer_regexp : float_regexp;if (regexp.test(this.value)) {this.value = this.value.replace(regexp, '');}});
$("#txt").on("keypress",function(e){console.log("Entered Key is " + e.key);switch (e.key){case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":case "0":case "Backspace":return true;break;
case ".":if ($(this).val().indexOf(".") == -1) //Checking if it already contains decimal. You can Remove this condition if you do not want to include decimals in your input box.{return true;}else{return false;}break;
default:return false;}});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Enter Value<input id="txt" type="text" />
var inputFilter = function (elem, cb) {/** /^-?\d*$/ restricts input to integer numbers* /^\d*$/ restricts input to unsigned integer numbers* /^[0-9a-f]*$/i restricts input to hexadecimal numbers* /^-?\d*[.,]?\d*$/ restricts input to floating point numbers (allowing both . and , as decimal separator)* /^-?\d*[.,]?\d{0,2}$/ restricts input to currency values (i.e. at most two decimal places)*/bdy.on('input keydown keyup mousedown mouseup select contextmenu drop', elem, function () {if (cb(this.value)) {this.oldValue = this.value;this.oldSelectionStart = this.selectionStart;this.oldSelectionEnd = this.selectionEnd;} else if (this.hasOwnProperty('oldValue')) {this.value = this.oldValue;this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);}});};
用法:
inputFilter('#onlyDigitsInput', function (val) {return /^\d*$/.test(val);});