jQuery regex can match numbers, but not hyphens - javascript

So, I would like to limit an input field to only allow numbers and hyphens. I'm not interested in changing my methodology, but would like to understand why my regex matches numbers but not hyphens.
Regex:
/[^0-9-]/g
jsFiddle: http://jsfiddle.net/abriggs/7G6JD/

Problem was with keycode of - ,
keycode of - is 189 or 109 .
But
String.fromCharCode(189) is ½
String.fromCharCode(109) is m
You can use the following code :
function numbersOnly(number, allowDash) {
// Filter non-digits/dash from input value.
console.log(number);
if (allowDash) {
number = number.replace(/[^0-9\-]/g, '');
} else {
// Filter non-digits from input value.
number = number.replace(/\D/, '');
}
return number;
}
$(function(){
// Do not allow non-numeric characters in bill zip code
$('#billZip').keydown(function(e) {
console.log(e.keyCode);
if (e.keyCode != 8 && e.keyCode != 37 && e.keyCode != 39) {
if(e.keyCode ===189||e.keyCode ===109)
if (numbersOnly(String.fromCharCode(45), true) != "")
return true;
else
return false
if (numbersOnly(String.fromCharCode(e.which), true) != "")
return true;
else return false
}
});
});
Fiddle

Adding simple console lines will show the error
function numbersOnly(number, allowDash) {
console.log("In numbersOnly);
// Filter non-digits/dash from input value.
if (allowDash) {
console.log("1:", number);
number = number.replace(/[^0-9\-]/g, '');
console.log(2:", number);
} else {
// Filter non-digits from input value.
number = number.replace(/\D/, '');
}
return number;
}
Type in 1
In numbersOnly
1: 1
2: 1
Type in -
In numbersOnly
1: ½
2:
So your problem is with the line String.fromCharCode(e.which)

The only way to do this is to have the hyphen as the FIRST or LAST character within the character class such as this:
[-0-9] or [0-9-]
However, you are using a "^" which negates everything in the character class, so if you only want hyphens and numbers you should not have the caret.
Source: http://www.regular-expressions.info/charclass.html

Related

Preventing the user from typing certain characters?

I need a field which can only take numbers, but not allow for signs such as "+", "-", "*" and "/". 0 can also not be the first number. If I make an Input field and set it's type to "number" I'm still allowed to write at least "+" and "-", and I can't quite seem to prevent the user from writing 0 as the first number either.
$('input#update-private-ext').on('keydown', function (e) {
var value = String.fromCharCode(e.keyCode);
if ($(this).text.length == 0 && value == 0) {
return false;
}
});
The above was my first attempt at making the function disallow 0 as the first character, but it doesn't seem to work. It just lets me write 0 as the first character. I also tried this to stop the signs from showing up:
$('input#update-private-ext').on('keydown', function (e) {
var badChars = '+-/*';
var value = String.fromCharCode(e.keyCode);
if ($(this).text.length == 0 && value == 0) {
return false;
}
if (badChars.indexOf(value) == -1) {
return false;
}
});
But with the badChars check, I cannot write anything in my field. So what am I missing here?
You should use e.key to get the current key pressed. String.fromCharCode(e.keyCode) gives the wrong result.
Also you should check if the bad chars is not -1. If it is, then your char is not a bad character and so you should not enter the if.
If you want to get the length of the input field you should use jQuery's .val() and not .text(). Or you can simply do it without jQuery using this.value.length.
$('input#update-private-ext').on('keydown', function (e) {
var badChars = '+-/*';
var value = e.key;
if (this.value.length == 0 && value == '0') {
return false;
}
if (badChars.indexOf(value) !== -1) {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="update-private-ext">
When you compare numbers and strings you must remember that numbers are encoded by using character codes from 48 to 57 and comparing strings with numbers is error-prone in JavaScript as there are many implicit coercions. You should be comparing objects of the same type to avoid the confusion.
In your case, the comparison should be done in the way that parsed string from the String.fromCharCode equals '0' - zero character (string), not the 0 as a number.
There are also issues of the keyCode parsing which yield strange values for the symbols because you would have to manually consider if Shift and other meta keys are pressed when parsing. Save yourself a trouble and just use e.key to get parsed key value.
By the way, please see the difference between this and $(this). Basically, in your case, it means that real instance of the input field is the first element of JQuery iterator - $(this)[0]. You may then just use this, which is automatically set to the target element in the event handler.
Please see the following example of blocking first 0 with debug information printed out:
$('input#update-private-ext').on('keydown', function (e) {
var value = e.key;
console.log('Typed character:');
console.log(value);
console.log('$(this)');
console.log($(this));
console.log('this (input element):');
console.log(this);
console.log("input's value:");
console.log(this.value);
if (this.value.length == 0 && value == '0') {
console.log('blocked');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="update-private-ext" />
In order to block other characters you can just filter them the following way (remember that indexOf returns -1 when the index is not found):
$('input#update-private-ext').on('keydown', function (e) {
var badChars = '+-/*';
var value = e.key;
if (this.value.length == 0 && value == '0') {
return false;
}
//Please note NOT EQUALS TO -1 which means not found.
if (badChars.indexOf(value) !== -1) {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="update-private-ext" />
You can do something like this below:
1. Check for bad chars if badChars.indexOf(v) >= 0.
2. Disallow starting from 0 by checking if the input starts from 0 and if yes, set the input field to blank.
This can give you a start!
$('input#update-private-ext').on('keydown', function(e) {
var badChars = '+-/*';
var v = e.key;
if (badChars.indexOf(v) >= 0) {
return false;
}
if ($(this).val().startsWith('0')) {
$(this).val("");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="update-private-ext" />

Delete a group of characters when backspace is pressed (Javascript)

I have a textarea that contains new lines initialized by a number and a period:
<textarea autoFocus id="text-area"wrap="hard"
defaultValue ={this.state.textAreaVal} onKeyUp={this._editTextArea}/>
To illustrate this:
Line 1
Line 2
Line 3
I have a function that is called onKeyDown to check if the keycode is a backspace:
_editTextArea: function(event) {
var key = event.keyCode;
if (key == 8) {
//remove the whole line if the previous characters are a number followed by a period and then a space
} else {
return true;
}
},
My goal here is to delete the number and period with one backspace (how its done in microsoft word, imagine having an ordered list when you get to the bulletpoint or number or roman numeral and you press backspace, it not only deletes the whole list item but also it returns you to the previous list item's last char.
How can I accomplish this?
Try this, should give you enough to go on.
<p id="demo"></p>
<script>
function myFunction() {
var str = "Hello world! 12.";
while (str.substring(str.length-1) == "." || isNumber(str.substring(str.length-1)))
{
str = str.substring(0,str.length-1)
}
document.getElementById("demo").innerHTML = str;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
</script>
I don't know exactly what you want but this maybe could help you:
$('textarea').keyup(function (e) {
if (e.keyCode == 8) {
e.preventDefault();
var lines = $('textarea').val().split('\n');
lines.splice(this.value.substr(0, this.selectionStart).split("\n").length-1, 1);
$('textarea').val(lines.join("\n"));
}
})
You can try it here:
https://jsfiddle.net/swnhe2f0/1/

JavaScript for float and integer number validation

I tried to make a javascript function to validate integer values from a text box. What is the best way to validate it so that only integer and float values are acceptable?
Required java script function for number validation.
// remove whitespaces
var input = input.replace(/\s+/g,"");
// check if the input is a valid number
if(isFinite(input) && input != ''){
// do your thing
}
Remember that isFinite only accepts values like '20.50' and not '20,50' as is custom in some countries. If you need this kind of flexibility you need to do additional string preprocessing. And with this solution only spaces are allowed as thousand delimiters (e.g '100 000').
Unfortunately the check for an empty string is necessary since isFinite('') returns true.
You could also use this function from user CMS (for a detailed explanation see: Validate decimal numbers in JavaScript - IsNumeric())
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Best ever solution for me for numeric validation in javascript.
function isFloat(evt) {
var charCode = (event.which) ? event.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
alert('Please enter only no or float value');
return false;
}
else {
//if dot sign entered more than once then don't allow to enter dot sign again. 46 is the code for dot sign
var parts = evt.srcElement.value.split('.');
if (parts.length > 1 && charCode == 46)
{
return false;
}
return true;
}
}
Just Copy and past javascript code and apply to your textbox onkeypress like this ..
<input type="text" onkeypress="return isFloat(event)" />
onload =function(){
var ele = document.querySelectorAll('.number-only')[0];
ele.onkeypress = function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
return false;
}
ele.onpaste = function(e){
e.preventDefault();
}
}
<input class="number-only" type=text />
JavaScript has a built in function, isNaN(text). Just pass the text of your text box to this function to get a Boolean result.
var valid = !isNaN(value);
Eg:
!isNaN('0'); // true
!isNaN('34.56'); // true
!isNaN('.34'); // true
!isNaN('-34'); // true
!isNaN('foo'); // false
!isNaN('08'); // true
!isNaN(''), !isNaN(' '), !isNaN('\n\t'), etc are all true!
Whitespace test + isNaN FTW:
var valid = !/^\s*$/.test(value) && !isNaN(value);

HTML textfield whose values cannot be 0 using Javascript

I was trying to make a javascript function which will check if the user entered value inside a text field cannot be less than 9 digits & it cannot be all 0s.
This is what I made
function CheckField(field)
{
if (field.value.length <9 || field.value=="000000000")
{
alert("fail");
field.focus();
return false;
}
else
{
return true;
}
}
<input type ="text" id="number1" onBlur='return CheckField(this)'>
But this doesnt check the condition where user enters more than 9 values and all 0's. It checks only for 1 condition that is with exact 9 zeros 000000000
So, if I understand that right you want the user to be able to enter a number with more than 9 digits, but they cannot be all zeros, right?
This can be done with a regexp:
var value; // Obtain it somehow
if (/^\d{9,}$/.test(value) && !/^0+$/.test(value)) {
// ok
}
What this checks is whether the value is at lest 9 digits (it does not allow anything but digits) and that they are not all 0s.
This should check for both conditions:
function CheckField(field){
return !/0{9}/.test(field.value) && /\d{9}/.test(field.value);
}
Try something like this:
var valueEntered = field.value;
if (parseInt(valueEntered) == 0) ...
or if you wanted to check if it was a number as well:
if (!(parseInt(valueEntered) > 0))
Two options spring to mind. You can try parsing the value as a number and test for isNaN or != 0
var parsed = parseInt(field.value, 10);
if(field.value.length < 9 || !(isNaN(parsed) || parsed != 0)){
alert("fail");
... rest of code
}
Or you could use a regex
if(field.value.length < 9 || !/[^0]/.test(field.value){
alert("fail");
... rest of code
}
The first option is probably quicker.
try this:
if (field.value.length <9 || field.value.replace("0","") == "")

JavaScript - Test for an integer

I have a text field that allows a user to enter their age. I am trying to do some client-side validation on this field with JavaScript. I have server-side validation already in place. However, I cannot seem to verify that the user enters an actual integer. I am currently trying the following code:
function IsValidAge(value) {
if (value.length == 0) {
return false;
}
var intValue = parseInt(value);
if (intValue == Number.NaN) {
return false;
}
if (intValue <= 0)
{
return false;
}
return true;
}
The odd thing is, I have entered individual characters into the textbox like "b" and this method returns true. How do I ensure that the user is only entering an integer?
Thank you
var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
alert('I am an int');
...
}
That will absolutely, positively fail if the user enters anything other than an nonnegative integer.
For real int checking, use this:
function isInt(value) {
return !isNaN(parseInt(value,10)) && (parseFloat(value,10) == parseInt(value,10));
}
The problem with many int checks is that they return 'false' for 1.0, which is a valid integer. This method checks to make sure that the value of float and int parsing are equal, so for #.00 it will return true.
UPDATE:
Two issues have been discussed in the comments I'll add to the answer for future readers:
First, when parsing string values that use a comma to indicate the decimal place, this method doesn't work. (Not surprising, how could it? Given "1,001" for example in the US it's an integer while in Germany it isn't.)
Second, the behavior of parseFloat and parseInt has changed in certain browsers since this answer was written and vary by browser. ParseInt is more aggressive and will discard letters appearing in a string. This is great for getting a number but not so good for validation.
My recommendation and practice to use a library like Globalize.js to parse numeric values for/from the UI rather than the browser implementation and to use the native calls only for known "programmatically" provided values, such as a string parsed from an XML document.
use isNaN(n)
i.e.
if(isNaN(intValue))
in place of
if (intValue == Number.NaN)
UPDATE
I have fixed the code that had an error and added a var called key to store the key pressed code using keyCode and which, that depend of the browser.
var key = e.which || e.keyCode;
Thanks Donald.McLean :)
If you want to check if you are writing numbers while typing (and avoid writing other characters into your input field), you can use this simple function and you can define the elements allowed (this include whatever you want to filter). In this way you can choose not only integers but for example a certain group of characters. The example is based in jQuery to attach it to an input field.
$('#myInputField').keypress(function(e)
{
var key = e.which || e.keyCode;
if (!(key >= 48 && key <= 57) && // Interval of values (0-9)
(key !== 8) && // Backspace
(key !== 9) && // Horizontal tab
(key !== 37) && // Percentage
(key !== 39) && // Single quotes (')
(key !== 46)) // Dot
{
e.preventDefault();
return false;
}
});
If you use other key than the defined, it won't appear into the field. And because Angular.js is getting strong these days. this is the directive you can create to do this in any field in your web app:
myApp.directive('integer', function()
{
return function (scope, element, attrs)
{
element.bind('keydown', function(e)
{
var key = e.which || e.keyCode;
if (!(key >= 48 && key <= 57) && // Interval (0-9)
(key !== 8) && // Backspace
(key !== 9) && // Horizontal tab
(key !== 37) && // Percentage
(key !== 39) && // Single quotes (')
(key !== 46)) // Dot
{
e.preventDefault();
return false;
}
});
}
});
But what happens if you want to use ng-repeat and you need to apply this directive only in a certain number of fields. Well, you can transform the upper directive into one prepared to admit a true or false value in order to be able to decide which field will be affected by it.
myApp.directive('rsInteger', function() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
if (attrs.rsInteger === 'true') {
element.bind('keydown', function(e)
{
var key = e.which || e.keyCode;
if (!(key >= 48 && key <= 57) && // Interval (0-9)
(key !== 8) && // Backspace
(key !== 9) && // Horizontal tab
(key !== 37) && // Percentage
(key !== 39) && // Single quotes (')
(key !== 46)) // Dot
{
e.preventDefault();
return false;
}
});
}
}
}
});
To use this new directive you just need to do it in a input type text like this, for example:
<input type="text" rs-integer="true">
Hope it helps you.
I did this to check for number and integer value
if(isNaN(field_value * 1) || (field_value % 1) != 0 ) not integer;
else integer;
Modular Divison
Example
1. 25.5 % 1 != 0 and ,
2. 25 % 1 == 0
And
if(field_value * 1) NaN if string eg: 25,34 or abcd etc ...
else integer or number
function isInt(x) {return Math.floor(x) === x;}
If your number is in the 32bit integer range, you could go with something like:
function isInt(x) { return ""+(x|0)==""+x; }
The bitwise or operator forces conversion to signed 32bit int.
The string conversion on both sides ensures that true/false want be matched.
Nobody tried this simple thing?
function isInt(value) {
return value == parseInt(value, 10);
}
What's wrong with that?
You may use isInteger() method of Number object
if ( (new Number(x)).isInteger() ) {
// handle integer
}
This method works properly if x is undefined or null. But it has poor browser support for now
I found the NaN responses lacking because they don't pick up on trailing characters (so "123abc" is considered a valid number) so I tried converting the string to an integer and back to a string, and ensuring it matched the original after conversion:
if ("" + parseInt(stringVal, 10) == stringVal) { alert("is valid number"); }
This worked for me, up until the numbers were so large they started appearing as scientific notation during the conversion.
...so of course this means you could enter a number in scientific notation, but checking minimum and maximum values as well would prevent that if you so desire.
It will of course fail if you use separators (like "1,000" or "1.000" depending on your locale) - digits only allowed here.
If (enteredAge < "1" || enteredAge > "130") ......
Simple and it works....until they develop immortality

Categories