I have a price field in my form i should allow decimal or floating point numbers only , not characters and any other special and white spaces in my price field.
How could i get that?
This is my code :
$("#foo").blur(function() {
var price = $("#foo").value;
var validatePrice = function(price) {
return /^(\d*([.,](?=\d{3}))?\d+)+((?!\2)[.,]\d\d)?$/.test(price);
}
alert(validatePrice(price)); // False
});
Fiddle
First off, here's the corrected code:
$("#foo").blur(function() {
var price = $("#foo").val();
var validatePrice = function(price) {
return /^(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(price);
}
alert(validatePrice(price)); // False
});
You will need to test for empty values (undefined) separately. Also, if you want to allow negative values use:
/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(price);
This regular expression was lifted from the JQuery Validate plug-in by Jörn Zaefferer. I recommend you consider using that plug-in as it contains a lot of other features.
In HTML5 it supports checking validity natively if the browser supports it:
$("#foo").blur(function(){
alert(this.checkValidity());
});
Demo: http://jsfiddle.net/DerekL/6djkS/
You can always fall back to the good old ugly Regex if the browser does not support it.
Basing on the Number definition used in JSON:
(source: json.org)
(with the negative, scientific notation parts removed.)
var regex = /^\d*(.\d{2})?$/;
regex.test(price); //Boolean
For https://stackoverflow.com/a/21494842/1885344, the correct regex would be
var regex = /^\d*(\.\d{2})?$/;
regex.test(price); //Boolean
As it is now, it would permits all character as the decimal separator where as it should be only dot (.) character.
Related
I'm using the following code to negate the characters in the regexp. By checking the inverse, I can determine if the value entered is correctly formatted. Essentially, any digit can be allowed but only one decimal point (placed anywhere in the string.) The way I have it now, it catches all numerals, but allows for multiple decimal points (creating invalid floats.) How can I adjust this to catch more than one decimal points (since I only want to allow for one)?
var regex = new RegExp(/[^0-9\.]/g);
var containsNonNumeric = this.value.match(regex);
if(containsNonNumeric){
this.value = this.value.replace(regex,'');
return false;
}
Here is what I'm expecting to happen:
First, valid input would be any number of numerals with the possibility of only one decimal point. The current behavior: The user enters characters one by one, if they are valid characters they will show up. If the character is invalid (e.g. the letter A) the field will replace that character with ''(essentially behaving like a backspace immediately after filling the character in. What I need is the same behavior for the addition of one too many decimal points.
As I understand your question the code below might be what you are looking for:
var validatedStr=str.replace(/[^0-9.]|\.(?=.*\.)/g, "");
It replaces all characters other then numbers and dot (.), then it replaces all dots followed by any number of 0-9 characters followed by dot.
EDIT based on first comment - the solution above erases all dots but the last, the author wants to erase all but the first one:
Since JS does not support "look behind", the solution might be to reverse string before regex, then reverse it again or to use this regex:
var counter=0;
var validatedStr=str.replace(/[^0-9.]|\./g, function($0){
if( $0 == "." && !(counter++) ) // dot found and counter is not incremented
return "."; // that means we met first dot and we want to keep it
return ""; // if we find anything else, let's erase it
});
JFTR: counter++ only executes if the first part of condition is true, so it works even for strings beginning with letters
Building upon the original regex from #Jan Legner with a pair of string reversals to work around the look behind behavior. Succeeds at keeping the first decimal point.
Modified with an attempt to cover negatives as well. Can't handle negative signs that are out of place and special cases that should logically return zero.
let keep_first_decimal = function(s) {
return s.toString().split('').reverse().join('').replace(/[^-?0-9.]|\.(?=.*\.)/g, '').split('').reverse().join('') * 1;
};
//filters as expected
console.log(keep_first_decimal("123.45.67"));
console.log(keep_first_decimal(123));
console.log(keep_first_decimal(123.45));
console.log(keep_first_decimal("123"));
console.log(keep_first_decimal("123.45"));
console.log(keep_first_decimal("a1b2c3d.e4f5g"));
console.log(keep_first_decimal("0.123"));
console.log(keep_first_decimal(".123"));
console.log(keep_first_decimal("0.123.45"));
console.log(keep_first_decimal("123."));
console.log(keep_first_decimal("123.0"));
console.log(keep_first_decimal("-123"));
console.log(keep_first_decimal("-123.45.67"));
console.log(keep_first_decimal("a-b123.45.67"));
console.log(keep_first_decimal("-ab123"));
console.log(keep_first_decimal(""));
//NaN, should return zero?
console.log(keep_first_decimal("."));
console.log(keep_first_decimal("-"));
//NaN, can't handle minus sign after first character
console.log(keep_first_decimal("-123.-45.67"));
console.log(keep_first_decimal("123.-45.67"));
console.log(keep_first_decimal("--123"));
console.log(keep_first_decimal("-a-b123"));
I don't get how hard it is to discern a string containing a number from other strings in JavaScript.
Number('') evaluates to 0, while '' is definitely not a number for humans.
parseFloat enforces numbers, but allow them to be tailed by abitrary text.
isNaN evaluates to false for whitespace strings.
So what is the programatically function for checking if a string is a number according to a simple and sane definition what a number is?
By using below function we can test whether a javascript string contains a number or not. In above function inplace of t, we need to pass our javascript string as a parameter, then the function will return either true or false
function hasNumbers(t)
{
var regex = /\d/g;
return regex.test(t);
}
If you want something a little more complex regarding format, you could use regex, something like this:
var pattern = /^(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;
Demo
I created this regex while answering a different question awhile back (see here). This will check that it is a number with atleast one character, cannot start with 0 unless it is 0 (or 0.[othernumbers]). Cannot have decimal unless there are digits after the decimal, may or may not have commas.. but if it does it makes sure they are 3 digits apart, etc. Could also add a -? at the beginning if you want to allow negative numbers... something like:
/^(-)?(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;
There's this simple solution :
var ok = parseFloat(s)==s;
If you need to consider "2 " as not a number, then you might use this one :
var ok = !!(+s==s && s.length && s.trim()==s);
You can always do:
function isNumber(n)
{
if (n.trim().length === 0)
return false;
return !isNaN(n);
}
Let's try
""+(+n)===n
which enforces a very rigid canonical way of the number.
However, such number strings can be created by var n=''+some_number by JS reliable.
So this solution would reject '.01', and reject all simple numbers that JS would stringify with exponent, also reject all exponential representations that JS would display with mantissa only. But as long we stay in integer and low float number ranges, it should work with otherwise supplied numbers to.
No need to panic just use this snippet if name String Contains only numbers or text.
try below.
var pattern = /^([^0-9]*)$/;
if(!YourNiceVariable.value.match(pattern)) {//it happen while Name Contains only Charectors.}
if(YourNiceVariable.value.match(pattern)) {//it happen while Name Contains only Numbers.}
This might be insane depending on the length of your string, but you could split it into an array of individual characters and then test each character with isNaN to determine if it's a number or not.
A very short, wrong but correctable answer was just deleted. I just could comment it, besides it was very cool! So here the corrected term again:
n!=='' && +n==n'
seems good. The first term eliminates the empty string case, the second one enforces the string interpretataion of a number created by numeric interpretation of the string to match the string. As the string is not empty, any tolerated character like whitespaces are removed, so we check if they were present.
I am trying to use RegExp validation for a number that can have up to 5 numbers followed up one option decimal place. Like 48293 or 23.4 are good. 99.99 or 453543 are not. I wrote the following function:
function validateLoad(load_value) {
var matchValue = new RegExp('[0-9]{1,5}(\.[0-9]{1})?')
return matchValue.test(load_value)
}
However, this seems to return true for all numerical values, can anyone tell me how to fix this?
You need to use anchors to make sure the entire string (and not just a substring) is matched by the regex. Also, don't forget to double the backslashes if you construct the regex from a string (and drop the {1}, it's a no-op):
var matchValue = new RegExp('^[0-9]{1,5}(\\.[0-9])?$');
Using literal notation would avoid to escape backslashes :
function validateLoad(load_value) {
return /^\d{1,5}(\.\d)?$/.test(load_value)
}
I have a form that has a field that takes what a decimal value. The desired requirements for this decimal are that it be in the form ##.## with two numbers on each side of the decimal point.
I found a regex online that is supposed to validate the decimal, but instead views any input as invalid. Here is the code I have:
function validateDecimal(number)
{
eval("var stringvar=/^[-+]?([0-9]*\\.[0-9]{0,2})|([0-9]+)$/");
return stringvar.test(number);
}
And the call...
var numStr = document.getElementById('Amount');
if (!validateDecimal(numStr)) {
alert("Please enter a valid dollar amount in the form ##.##");
return false;
}
I understand that this regex is not exactly what I'm looking for, but I can't seem to figure out why it views all input as invalid. Does anyone know what I'm doing wrong?
The first problem is that you forgot to grab the actual value of your input:
document.getElementById('Amount').value
The second problem is eval, you don't need it here, you can write it like this:
var stringvar = /^[-+]?([0-9]*\.[0-9]{0,2})|([0-9]+)$/;
And third, here's the regex I propose if your number must always be XX.XX:
/^[+-]?\d\d\.\d\d$/
first off, you shouldn't be using eval like that, it puts unnecessary stress on the client, just do
var regex = /^[-+]?([0-9]*\\.[0-9]{0,2})|([0-9]+)$/;
return regex.test(number);
instead.
And you need to use .value after getElementById('Amount');
I have a page with some elements that are controlled by the user. One of these is a text input field, where the user is supposed to input a number. Everything works well if the user only inputs digits (EG 9000), but is the user uses comma notation (the being 9,000) javascript doesn't take the input as an integer.
How can I remove the commas and/or force the input to an integer? I tried using parseint(), but it doesn't seem to work with commas.
Use a global regular expression to replace all commas with an empty string:
var str = "12,345,678";
str = str.replace(/,/g, "");
parseInt(str, 10);
or even better
var s="jdjsghd0182.99";
var str = parseFloat(s.replace(/[^0-9 | ^.]/g, ''));
Or even better, given the general unreliability of user input, use this to get rid of all non-numeric characters:
var s = "9,Ljk876";
var t = parseInt(s.replace(/[^0-9]/g, ''));
alert ("s:" + s + ", t:" + t);
maybe
parseint(ny9000withCommas.replace(/\,/g,""))
lets talk about the restriction :
you can/should allow the user to enter both 9000 & 9,000
you can check validy via REGEX.
in the server side - you should eleminate the commas and treat it as integer.