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

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

Related

jquery keydown bind with regex does not validate for apostrophe and periods

I have been using jquery to capture the keydown event and validate the entered text for different cases like: characters only, alpha-numeric, characters and spaces etc.
Regex used:
Characters with spaces: ^[a-zA-Z ]+$
Characters only: ^[a-zA-Z]+$
Alphanumerics: ^[a-zA-Z0-9]+$
This is how I am using the bind function:
$('.chars_and_space_only').bind('keydown', function (event) {
// http://stackoverflow.com/a/8833854/260665
var eventCode = !event.charCode ? event.which : event.charCode;
if((eventCode >= 37 && eventCode <= 40) || eventCode == 8 || eventCode == 9 || eventCode == 46) { // Left / Right Arrow, Backspace, Delete keys
return;
}
// http://stackoverflow.com/a/8833854/260665
var regex = new RegExp("^[a-zA-Z ]+$");
var key = String.fromCharCode(eventCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
All of above uses cases are working fine, however I have to now include characters, spaces, apostrophe and periods. So this is the method I have modified:
$(".chars_space_dots_apostrophes_only").bind('keydown', function (event) {
// http://stackoverflow.com/a/8833854/260665
var eventCode = !event.charCode ? event.which : event.charCode;
if((eventCode >= 37 && eventCode <= 40) || eventCode == 8 || eventCode == 9 || eventCode == 46) { // Left / Right Arrow, Backspace, Delete keys
return;
}
// http://stackoverflow.com/a/8833854/260665
var regex = new RegExp("^[a-zA-Z '.]+$");
var key = String.fromCharCode(eventCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
This, strangely doesn't seem to work. Here is the fiddle: https://jsfiddle.net/ugu8f4y3/
Regex used: ^[a-zA-Z '.]+$
Regex validator does validate this text for the above regex:
Hello. World's
But the text field in fiddle does not allow me to enter periods and apostrophes, is there something I am missing here?
The problem is with jquery and the keydown event. Replace it with keypress and you'll be good to go. You should also only need to check in which.
keydown and keyup are important for cases when you're concerned with the position of the key's physical location. In this case you want to know that the key was depressed and handle the resulting input. jquery will normalize the character codes differently.
Further information about the differences between keypress, keydown and key up.
Updated Fiddle

jquery keypress in input text restriction, i want it to allow A-Z and white space only but my code won't allow "Y" and "Z"

Actually I didn't code this, i just copy and paste it to try.
Here's the code.
$("#firstname, #lastname").keypress(function(event) {
var inputValue = event.charCode;
if (!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
$('#input').html(inputValue);
});
The keycode for y is 121 and likewise the keycode for z is 122. Therefore if you want to include those in the range then you should change inputValue <= 120 to inputValue <= 122.
However, you don't need to check the keycodes for this. I'd suggest using the regular expression /[^a-z\s]/gi (which is a negated character class that will match characters that are not a-z or whitespace - case insensitive).
You can simply replace these characters with an empty string and effectively remove them:
$("#firstname, #lastname").on('input', function(event) {
this.value = this.value.replace(/[^a-z\s]/gi, '');
});
Basic example:
$("#firstname, #lastname").on('input', function(event) {
this.value = this.value.replace(/[^a-z\s]/gi, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="firstname" type="text" />

Allow arrow keys in Regular Expression

I am performing alphanumeric validation and now I am doing that user can only enter an alphanumeric value and also allow alphanumeric values only while pasting. So I used the following regular expression
function OnlyAlphaNumeric(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if ((charCode > 32 && charCode < 48) || (charCode > 57 && charCode < 65) ||
(charCode > 90 && charCode < 97) || charCode > 122) {
return false;
}
else {
return true;
}
}
And for preventing the copy and paste,
function CPOnlyAlphaNumeric(evt) {
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}
These two functions are calling from the following onkeypress and onkeyup methods such that is given below as shown that
#Html.TextBoxFor(model => model.ProductName, new { #class = "form-
control", #onkeypress = "return OnlyAlphaNumeric(this);", #onkeyup=
"return CPOnlyAlphaNumeric(this);" })
This works for alphanumeric validation, but it doesn't allow the cursor to move left side for editing the text. So what will change I should do in my Regular Expression.
Your problem has nothing related to regular expressions.
When you press any key (including left/right arrow) you take value of input, replace all forbidden characters and set the value of the input. When last action is done it's the browser native behavior to move the cursor to the end of input.
You can check what is the pressed key and if it's left/right arrow to skip the manipulation of input value.
function CPOnlyAlphaNumeric(evt) {
var code = evt.which ? evt.which : event.keyCode;
// 37 = left arrow, 39 = right arrow.
if(code !== 37 && code !== 39)
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}
Demo
However this is not a good solution because it will result in a terrible behavior (you won't be able to use shift for mark, the cursor will be moved at the end after first typed letter in the middle of word etc..)
A better solution could be to 'clean' the input value let's say 500 ms after user stop typing.
var timeout = null;
function CPOnlyAlphaNumeric(evt) {
if(timeout)
clearTimeout(timeout);
timeout = setTimeout(function(){
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}, 500);
}
Demo
Please note that you need to add the validation on server side as well (and maybe before the form submit, because user can hit enter to submit the form before the 'cleaning' of input is triggered).
You can try this, it may solve your problem.
var regex = new RegExp("^[a-zA-Z0-9]+$");
var charCode =(typeof event.which == "number") ?event.which:event.keyCode
var key = String.fromCharCode(charCode);
if (!(charCode == 8 || charCode == 0)) {
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
Problem with keyDown event is that you cant suppress the display of keys in the textfield (only alpha numeric in my case). You can do it in only keyPress event. But you cant get navigation keys in keyPress event, you can only track them in KeyDown event. And some of the keys $,%, have the same e.which that arrow keys has in keypress event. which is causing issues for me to write the logic to allow arrow keys but restrict the text to only Alpha numeric. Here is the code I came up with. Working fine now.
onKeyPress: function(e){
var regex = new RegExp("^[a-zA-Z0-9\b ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
var allowedSpecialKeys = 'ArrowLeftArrowRightArrowUpArrowDownDelete';
var key = e.key;
/*IE doesn't fire events for arrow keys, Firefox does*/
if(allowedSpecialKeys.indexOf(key)>-1){
return true;
}
if (regex.test(str)) {
return true;
}
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
return false;
}

how to find out keycode value of char in javascript

im having a slight issue, with trying to programmatically find out the keycode value of a char. this is what I have at the moment.
var delimiter = ',';
//some where down the page
control.keyup(function(e)
{
var key = delimiter .charCodeAt(0);
if(e.keycode == key)
{
//do something
}
}
So when I press the ',' on the keyboard key has a value of 44 whilst e.keycode is 188. How to find out the keycode value of the variable delimiter ?
The keyup event returns a keycode not an ASCII code. If you switch to the keypress event you can retreive the ASCII code. This should match the value received by charCodeAt which returns the unicode value of a character, which happens to align with the ASCII code for the first 128 characters. See this reference.
var delimiter = ',';
var key = delimiter.charCodeAt(0);
document.getElementById("test").onkeypress = function(e){
if((e.keyCode || e.which) == key){
alert("Cat's out of the bag! OHHH YEAH!");
}
};

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>

Categories

Resources