jquery plugin for preventing entering any input not matching a regexp - javascript

does jquery have any plugin that prevents entering any input to a textbox that doesnt match a regexp pattern. for example , i have a textbox for entering payment amount, i want user t be able to enter only numebers and . in the textbox, all other input wont have any effect on the textbox..
thanks

Masked Input Plugin
jQuery(function($){
$("#paymentAmount").mask("9999.99");
});

jquery-keyfilter plugin - does what is needed.

I don't think there is any such plugin readily available. The problem is a little tricky, because you have to allow the user to type some input before applying your regex. That is, you can't just match against each char as it is typed, unless your regex simply defines a set of characters.
To illustrate, if they are entering a payment amount, and you want to allow numbers and decimals on a single-character basis, what prevents them from entering 99.99.23.42492?
On the other hand, if you supply a complete regex like /\d+\.\d{2}/, then it won't match at all on a single character, you'll have to allow them to type some number of characters before trying to apply the regex and wiping out their input if it doesn't match. That could be frustrating.
If you really want to filter the input as they type, then you want to allow a digit for the first character, then digits or a decimal for subsequent characters until the decimal is entered, and then two more digits, and then no more input. It's not a general-purpose filter.
For example, here's some code that will do that, but it's very ugly.
myInput.keydown(function() {
var text = this.val
if(!/^\d/.test(text)) {
return '';
} else {
done = text.match(/^(\d+\.\d\d)/);
if (done) { return done[0]; }
last_char = text.substr(text.length-1,1);
decimal_count = text.replace(/[^\.]/g,'').length;
if (decimal_count < 1) {
if (!/[\d\.]/.test(last_char)) {
return text.substr(0,text.length-1);
}
} else if (decimal_count == 1 && last_char == '.') {
return text;
} else {
if (!/[\d]/.test(last_char)) {
return text.substr(0,text.length-1);
}
}
return text;
}
});
And of course, this won't work if they happen to paste in certain values without doing "real" typing.
Maybe some other approach would work better for you? Like highlighting the field and indicating to the user if they enter a non-digit, non-decimal, or if they enter more than one decimal, rather than filtering the input itself, because that seems messy.

Keyboard events are a bit tricky as suggested on the jQuery docs.
http://unixpapa.com/js/key.html
http://yehudakatz.com/2007/07/03/event-normalization-in-jquery-113/
The difficulty that concerns you is this:Identifying Keys
When you catch a keyboard event, you may wish to know which key was pressed. If so, you may be asking too much. This is a very big mess of browser incompatibilities and bugs.
From the first link above
All the same, in jQuery I'd do this:
textBoxElement.keydown( function( e ) {
var chr = String.fromCharCode( e.which );
if( !/[0-9.]/.test( chr ) ) {
e.preventDefault();
}
}
This will also disable other important keys like enter, tab, delete, so they need to be added into the conditional. Not all the other keys are printable and so can't be regexed, so you'll have to check for their e.keyCode. 13, 8 etc.
If you're not too bothered about the regex you could do something like
textBoxElement.keydown( function( e ) {
switch( e.keyCode ) {
case 48: //0
case 49: //1
case 50: //2
case 51: //3
case 52: //4
case 53: //5
case 54: //6
case 55: //7
case 56: //8
case 57: //9
case 48: //10
case 37: //left
case 39: //right
case 8: //tab
case 13: //return
case 46: //del
case 190: //.
return;
}
e.preventDefault();
});

Here is a simple jquery extension I use:
jQuery.fn.DecimalMask = function () {
return this.each(function () {
$(this).keypress(function (e) {
var keynum;
if (window.event) // IE
{
keynum = e.keyCode;
}
else if (e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
if (typeof keynum == 'undefined') return true;
else if (keynum == 46 && $(this).val().indexOf(".") > -1) return false; //already has a decimal point
else return ((keynum > 47 && keynum < 58) || keynum == 13 || keynum == 8 || keynum == 9 || keynum == 46 || keynum == 45); //allow ony number keys or keypad number keys
});
});
};
//implementation
$("#mytxtbox").DecimalMask();

Related

Regex for negative decimal values client and server side c# jquery

I have a keypress function bound to an element, this element needs to only allow positive and negative decimal characters. i.e. 0-9, '.' , '-'
any other characters I need to prevent the character being inputted
Is there any way to achieve this in the current keypress function
$('.test').keyup(function (event) {
//if character is NOT ok i.e. 0-9, '.' , '-'
//STOP
..ELSE
//continue to do something
});
P.s. I am using jquery
One other way is to replace all illegal characters when typing:
$("selector").keyup(function (e) {
this.value = this.value.replace(/[^0-9\.-]/g, '');
});
May be useful, when user not typing text, but pasting it.
The key is inserted on keydown, so you should use that event instead. Then this should work:
$('.test').on('keyup', function(e){
e.preventDefault();
if(e.keyCode >= 48 && e.keyCode <= 57 // regular numbers
|| e.keyCode >= 96 && e.keyCode <= 106 // Numpad
|| e.keyCode === 189 // Minus
){
try{
parseInt($(this).val());
// Continue, this is a valid numeric value.
}catch(ex){
// Stop
}
}else {
// Stop
}
});
Hope this helps:
var string = '-10.56',
illegal = /[^0-9.-]/.test(string); // return true if illegal character found

RegEx in Javascript to allow negative decimal input to a text field

I have a requirement wherein i need to allow plus/minus sign in the beginning followed by a decimal number which allows only one dot in it in a text field input in html.
Bascially the text field should allow normal integer numbers and decimal numbers and also negative integer and negative decimal numbers. The plus and minus sign should be allowed only in the beginning (first character) and it's optional. Also should allow any number of decimal places (ex: -12.12345 etc) but only one decimal (dot) in the entry.
Digits allowed are: 1, + 1, -1, .1, +1.1, -1.1, -.12, +.12, 123.4456, -123.345, +123.345 etc
Any help is highly appreciated.
I'm using below regex for the above requirement.
var integerOnly = /[\+\-0-9\.]/g;
and below script (which i obtained from some other thread with slight modification) to validate it .
function restrictInput(myfield, e, restrictionType, checkdot){
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
alert("1 " + character);
// if user pressed esc... remove focus from field...
if (code==27) { this.blur(); return false; }
//alert("2");
// ignore if the user presses other keys
// strange because code: 39 is the down key AND ' key...
// and DEL also equals .
if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
alert("3");
if (character.match(restrictionType)) {
alert("4");
if(checkdot == "checkdot" & '-' != character & '+' != character){
alert("5");
return !isNaN((myfield.value.toString()==''? '0':myfield.value.toString())+character );
} else {
return true;
}
} else {
return false;
}
}
}
Here is how the script is called.
<input type="text" id="db" width="3" value="" onkeypress="return restrictInput(this, event, integerOnly, 'checkdot');"/>
It works fine except for few cases like:
It allows +/- any place any number of times. My requirement is to allow only at the beginning.
I tried to modify the regex as below.
var integerOnly = /[\+\-]?[0-9\.]/g;
In that case, it doesn't match the expression. It doesn't reach alert 4.
One thing is it allows only one decimal places and not more than one.
Can someone help me to modify my regular expression so as to allow only +/- in the beginning and only once.
Thank you.
Instead of playing with regex, validate your text using isNumber function as follows
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
I think that you want something like this:
^[-+]?(\d+\.?|\d*\.\d+)$
As the digits before the decimal separator or the digits after are optional (e.g. 1. or .1) but noth both, you need to handle the cases separately.
var test_ary = ['1', '+1', '-1', '.1', '+1.1', '-1.1', '-.12', '+.12', '123.4456', '-123.345', '+123.345'];
var reg = /^[\+\-]?(?:\.?\d+|\d+\.?\d+)$/;
var i;
for ( i = 0; i < test_ary.length; i = i + 1) {
console.log(reg.test(test_ary[i]));
}
you can also try this, with test case :)
I took 'niksvp' script and modified a bit to meet my requirement.
The below script works for all types of +/- decimal numbers. ex: 1.1, +1.1, -1.1, .1, -.1, +.1, 1, -1, +1, 123.345, +123.345, -123.345 etc
function isNumber(myfield, e) {
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
var n = myfield.value.toString()==''? '0':myfield.value.toString();
// this is required to allow numbers of this format
// -1.1, + 1.1, .1, -.1, +.1 etc
if(n == '-' | n == '+' | n== '.') {
n +=0;
}
if(n.length > 1) {
n = n.toString() + character;
}
return !isNaN(parseFloat(n)) && isFinite(n);
}
Thanks to all for your help.

Validate character amount, text length and decimal places from input using javascript

I am using a javascript to validate input from a textbox that's inside a ASPxGridView control(DevExpress component).
I am using this javascript code to validate it(thru OnKeyPress event):
function CheckKey(s, e) {
var key = ASPxClientUtils.GetKeyCode(e.htmlEvent);
var char = String.fromCharCode(key);
if (e.htmlEvent.shiftKey) {
if (!IsAvailableChar(char))
ASPxClientUtils.PreventEvent(e.htmlEvent);
} else
if (!(IsAvailableChar(char) || IsAvailableKey(key))) ASPxClientUtils.PreventEvent(e.htmlEvent);
return;
}
function IsAvailableChar(char) {
var AvailableChars = "0123456789,";
return AvailableChars.indexOf(char) != -1;
}
function IsAvailableKey(key) {
switch (key) {
case 46: //delete
return true;
break;
case 37: //left arrow
return true;
break;
case 39: //right arrow
return true;
break;
case 16: //shift
return true;
break;
case 188: //comma
return true;
break;
default:
return false;
break;
}
I use this to "block" some characters and it works fine.
But now I wanna do something a little bit more complicated: I don't want the user to input more than one comma in the textbox.
A little bit more complicated than that: the maxlength of this textbox is 6. I want it to allow two decimal places only and the maximum of three numbers before the decimal places.
For example:
I want it to allow these strings: "123,12", "45,32", "7,65", "9,6", "85,32", "94,1", "310,2".
I don't want it to allow these strings: "1,123", "125,789", "1234,2"
Any ideas on how I can do that?
Thank you!
Edit:
I tried to use the two regular expressions you guys told me to like this:
function CheckKey(s, e) {
var key = ASPxClientUtils.GetKeyCode(e.htmlEvent);
var char = String.fromCharCode(key);
var text = document.getElementsByName(s.uniqueID)[0].value + char;
var regEx = new RegExp("/^\d{0,3}(,\d{0,2})?$/");
if(regEx.test(text))
return;
else
ASPxClientUtils.PreventEvent(e.htmlEvent);
return;
}
However, regEx.test(text) is always returning false, even when the input matches the regular expression.
Another edit:
I changed the instantiation of the RegExp object in the code above from this:
var regEx = new RegExp("/^\d{0,3}(,\d{0,2})?$/");
To this:
var regEx = /^\d{0,3}(,\d{0,2})?$/
And now it worked, thank you!
/^\d{0,3}(,\d{0,2})?$/.test(textbox.value + char);
This will match any number with as many as three pre-decimal places. Optionally, it allows a decimal and up to 2 decimal places. Also matches the empty string, for ease of use. So this will check to make sure the resultant box matches.
An explanation of the regEx:
^
Start of string
\d{0,3}
0 to 3 digits (inclusive)
(...)?
An optional group
,\d{0,2}
A comma followed by 0 to 2 digits (inclusive)
$
End of string.
var regex_test = /^[1-9][0-9]{0,2},[0-9][0-9]{0,1}$/;
var string = '766,99';
if(regex_test.test(string)){
console.log('good');
}

How to know if .keyup() is a character key (jQuery)

How to know if .keyup() is a character key (jQuery)
$("input").keyup(function() {
if (key is a character) { //such as a b A b c 5 3 2 $ # ^ ! ^ * # ...etc not enter key or shift or Esc or space ...etc
/* Do stuff */
}
});
You can't do this reliably with the keyup event. If you want to know something about the character that was typed, you have to use the keypress event instead.
The following example will work all the time in most browsers but there are some edge cases that you should be aware of. For what is in my view the definitive guide on this, see http://unixpapa.com/js/key.html.
$("input").keypress(function(e) {
if (e.which !== 0) {
alert("Charcter was typed. It was: " + String.fromCharCode(e.which));
}
});
keyup and keydown give you information about the physical key that was pressed. On standard US/UK keyboards in their standard layouts, it looks like there is a correlation between the keyCode property of these events and the character they represent. However, this is not reliable: different keyboard layouts will have different mappings.
Note: In hindsight this was a quick and dirty answer, and may not work in all situations. To have a reliable solution, see Tim Down's answer (copy pasting that here as this answer is still getting views and upvotes):
You can't do this reliably with the keyup event. If you want to know
something about the character that was typed, you have to use the
keypress event instead.
The following example will work all the time in most browsers but
there are some edge cases that you should be aware of. For what is in
my view the definitive guide on this, see
http://unixpapa.com/js/key.html.
$("input").keypress(function(e) {
if (e.which !== 0) {
alert("Character was typed. It was: " + String.fromCharCode(e.which));
}
});
keyup and keydown give you information about the physical key that
was pressed. On standard US/UK keyboards in their standard layouts, it
looks like there is a correlation between the keyCode property of
these events and the character they represent. However, this is not
reliable: different keyboard layouts will have different mappings.
The following was the original answer, but is not correct and may not work reliably in all situations.
To match the keycode with a word character (eg., a would match. space would not)
$("input").keyup(function(event)
{
var c= String.fromCharCode(event.keyCode);
var isWordcharacter = c.match(/\w/);
});
Ok, that was a quick answer. The approach is the same, but beware of keycode issues, see this article in quirksmode.
I'm not totally satisfied with the other answers given. They've all got some kind of flaw to them.
Using keyPress with event.which is unreliable because you can't catch a backspace or a delete (as mentioned by Tarl).
Using keyDown (as in Niva's and Tarl's answers) is a bit better, but the solution is flawed because it attempts to use event.keyCode with String.fromCharCode() (keyCode and charCode are not the same!).
However, what we DO have with the keydown or keyup event is the actual key that was pressed (event.key).
As far as I can tell, any key with a length of 1 is a character (number or letter) regardless of which language keyboard you're using. Please correct me if that's not true!
Then there's that very long answer from asdf. That might work perfectly, but it seems like overkill.
So here's a simple solution that will catch all characters, backspace, and delete. (Note: either keyup or keydown will work here, but keypress will not)
$("input").keydown(function(event) {
var isWordCharacter = event.key.length === 1;
var isBackspaceOrDelete = event.keyCode === 8 || event.keyCode === 46;
if (isWordCharacter || isBackspaceOrDelete) {
// do something
}
});
This helped for me:
$("#input").keyup(function(event) {
//use keyup instead keypress because:
//- keypress will not work on backspace and delete
//- keypress is called before the character is added to the textfield (at least in google chrome)
var searchText = $.trim($("#input").val());
var c= String.fromCharCode(event.keyCode);
var isWordCharacter = c.match(/\w/);
var isBackspaceOrDelete = (event.keyCode == 8 || event.keyCode == 46);
// trigger only on word characters, backspace or delete and an entry size of at least 3 characters
if((isWordCharacter || isBackspaceOrDelete) && searchText.length > 2)
{ ...
If you only need to exclude out enter, escape and spacebar keys, you can do the following:
$("#text1").keyup(function(event) {
if (event.keyCode != '13' && event.keyCode != '27' && event.keyCode != '32') {
alert('test');
}
});
See it actions here.
You can refer to the complete list of keycode here for your further modification.
I wanted to do exactly this, and I thought of a solution involving both the keyup and the keypress events.
(I haven't tested it in all browsers, but I used the information compiled at http://unixpapa.com/js/key.html)
Edit: rewrote it as a jQuery plugin.
(function($) {
$.fn.normalkeypress = function(onNormal, onSpecial) {
this.bind('keydown keypress keyup', (function() {
var keyDown = {}, // keep track of which buttons have been pressed
lastKeyDown;
return function(event) {
if (event.type == 'keydown') {
keyDown[lastKeyDown = event.keyCode] = false;
return;
}
if (event.type == 'keypress') {
keyDown[lastKeyDown] = event; // this keydown also triggered a keypress
return;
}
// 'keyup' event
var keyPress = keyDown[event.keyCode];
if ( keyPress &&
( ( ( keyPress.which >= 32 // not a control character
//|| keyPress.which == 8 || // \b
//|| keyPress.which == 9 || // \t
//|| keyPress.which == 10 || // \n
//|| keyPress.which == 13 // \r
) &&
!( keyPress.which >= 63232 && keyPress.which <= 63247 ) && // not special character in WebKit < 525
!( keyPress.which == 63273 ) && //
!( keyPress.which >= 63275 && keyPress.which <= 63277 ) && //
!( keyPress.which === event.keyCode && // not End / Home / Insert / Delete (i.e. in Opera < 10.50)
( keyPress.which == 35 || // End
keyPress.which == 36 || // Home
keyPress.which == 45 || // Insert
keyPress.which == 46 || // Delete
keyPress.which == 144 // Num Lock
)
)
) ||
keyPress.which === undefined // normal character in IE < 9.0
) &&
keyPress.charCode !== 0 // not special character in Konqueror 4.3
) {
// Normal character
if (onNormal) onNormal.call(this, keyPress, event);
} else {
// Special character
if (onSpecial) onSpecial.call(this, event);
}
delete keyDown[event.keyCode];
};
})());
};
})(jQuery);
I never liked the key code validation. My approach was to see if the input have text (any character), confirming that the user is entering text and no other characters
$('#input').on('keyup', function() {
var words = $(this).val();
// if input is empty, remove the word count data and return
if(!words.length) {
$(this).removeData('wcount');
return true;
}
// if word count data equals the count of the input, return
if(typeof $(this).data('wcount') !== "undefined" && ($(this).data('wcount') == words.length)){
return true;
}
// update or initialize the word count data
$(this).data('wcount', words.length);
console.log('user tiped ' + words);
// do you stuff...
});
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="text" name="input" id="input">
</body>
</html>

js backspace and counting how many digits

i have this code for counting how many digits where entered
var tnnod=0;
function telephone(e) {
if (tnnod<10) {
var key;
var keychar;
if (window.event) {
key = window.event.keyCode;
}
else if (e) {
key = e.which;
}
else {
return true;
}
keychar = String.fromCharCode(key);
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) ) {
return true;
}
else if ((("0123456789").indexOf(keychar) > -1)) {
tnnod+=1;
return true;
}
else if (keychar == "-") {
return true;
}
else
return false;
}
else
return false
}
but how do i remove 1 from the counter each time the backspace was hitted and the char that was deleted was a digit and not "-"
i have tried getting the key == 8 to do something but hitting the backspace doesn't really return anything for some reason
what can be the problem?
You don't have to detect specifically the backspace keypress. Try this:
var tn_count = 0;
function telephone(ev) {
var el = document.getElementById("telephone_number");
if(tn_count < 10) {
var key, keychar;
if(window.event) {
key = window.event.keyCode;
} else {
key = ev.which;
}
keychar = String.fromCharCode(key);
}
if(!keychar.match(/\d|-/)) { // only allow digits or "-"
return false;
}
// clean up any non-digit chars that get in here somehow
el.value = el.value.replace(/[A-Za-z]+/, '');
tn_count = el.value.replace("-",'').length; // get the digit length
return true;
}
The basic difference here is that instead of adding 1 every time the key is pressed, just updated tn_count to be the total count of all digit characters in the field. You can probably do some more cleanup just to be safe, but this should get you started.
I think it's a bad idea to count keystrokes for something like that. We're talking about input into a text field, right? What will you do if the user does a paste of some string from the clipboard? What if he uses the mouse to mark some text and delete it? Replace it with one character?
I think it would make a lot more sense to just look at the text from the text field and (if necessary) do some fiddling to ensure proper syntax. Let the user enter whatever he wants, if you find garbage characters you can just replace the text with one that doesn't have those characters. You can also trim the field at this time (no leading or trailing spaces). Also, keeping accurate track of the length becomes as easy as asking for the length of the string returned from the field.
A few thoughts -
Would it be possible to use 3 fields instead of 1? Then you could add the dashes later.
If you want to use your current method, you might keep a counter of the dashes that have been typed. Then, on each key stroke, check to see how many dashes are left. If it's different than the previous count, you know they've deleted the dashes.
I think it needs to be a bit more robust. What if they put a dash in an odd place within the string?
You could also prevent the user from entering all non-numeric characters and insert the dashes at each point of separation. So, insert a dash after 3 and 6 numbers as they are typing.
Could you just count the length of the string and use that value? Something like the following:
function getLen(el) {
return el.value.replace('-', '').length;
}
alert(getLen(document.getElementById('telephone_number')));

Categories

Resources