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');
Related
I have one requirement in form.My form has textbox field "DEA License number".textbox must allow user to enter alphabet only for first two characters and numbers only after two characters.I want to achieve this functionality using javascript.Note:-I dont want validation but avoid user inputting
Have you tried using regex?
Take a look at this post which has a very similar goal: RegEx pattern any two letters followed by six numbers
Try use some of masked textbox.
For example:
https://css-tricks.com/input-masking/
http://digitalbush.com/projects/masked-input-plugin/
You can easily test this with a regex:
function isValid(str) {
return /^[a-zA-Z]{2}\d+$/.test(str);
}
I am not quite sure what you mean by "I dont want validation but avoid user inputting." If you mean that you don't want the user to be able to type an invalid character, this could theoretically be done with an input event handler:
var oldValue = "";
document.getElementById("test").addEventListener("input", function(e) {
var value = e.target.value;
if ((value.length <= 2 && /^[a-zA-Z]*$/.test(value)) || value.length > 2 && /^[a-zA-Z]{2}\d+$/.test(value)) oldValue = value
else e.target.value = oldValue;
})
However, you'd still need to validate it when it's submitted since the user could've entered an incomplete value.
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 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.
I am using a regular expression to validate input from a text field to only allow a whole number or a number with up to two decimal places (eg: 10, 10.4, 10.45, 100.45) ,however when I enter a number with 3 or more decimal places it will still validate it. Code shown below.
var loanAmount = document.getElementById("loan_amount");
var loanRE = /\d+(\.\d{1,2})?/;
if (!(loanRE.test(loanAmount.value))){
alert("Not a valid input for the loan amount");
return false;
}
Everything looks good to me. What am I missing?
Anchor your regex. loadRE = /^\d+(\.\d{1,2})?$/
Otherwise it will just say "okay, there's some digits. It passes!"
I currently use the script below to take any form of information and pull out the numbers to make a phone number with dashes in it. However, if I accidently click in the field, it puts two dashes in there even though nothing was pasted or typed. Does JS have a way to say ONLY if something is pasted then add dashes? The reason it's a pain is I have 2 search fields, and if I want to use one, the other has to be blank. So if there are 2 dashes in it, I have to delete them out and hit enter in the same field or it will add them again.
I appreciate any help you might have.
<SCRIPT LANGUAGE="JavaScript">
function addDashes(f)
{
f.value = f.value.replace(/\D/g, '');
f.value = f.value.slice(0,3)+"-"+f.value.slice(3,6)+"-"+f.value.slice(6,15);
}
</SCRIPT>
I'd go with something like this:
function addDashes(f) {
f.value = f.value.replace(/(\d{3})-?(\d{3})-?(\d{9})/, '$1-$2-$3');
}
It'll only do something if you have 15 digits there (possibly with dashes already in place).
I'm not quite sure if this is what you need, but this just checks to see if there is actually something there before formatting it:
function addDashes(f)
{
var oldVal = f.value.replace(/\D/g, '');
if (oldVal.length) {
f.value = oldVal.slice(0,3) + "-" + oldVal.slice(3,6) + "-" + oldVal.slice(6,15);
}
}
EDIT:
Based on your comment, I thought it might be helpful to bring up validation. I'm not sure if you are doing anything on the server-side to make sure it is a valid phone number, but it might be helpful to do a little validation so taht you don't add dashes if the user has just typed some spaces.
First, I would remove the non-numeric values before you check the length. I've updated the code above to do that.
Next, I would check against some length. Maybe you want to only add dashes if the number is at least 9 digits long. You can decide that length taht you watn to check against. In that case, you would add:
if (oldVal.length >= 9) { ...
It all depends on if/how you are validating this field.