How to validate for Values "0" or "00" or "000" for textfield which has the regex and some accepted values - javascript

var myregex = /^[0-9][0-9]{0,3}$|^[0-9][0-9]{0,3}[\.][0-9]$/;
if(!myregex.test($('#txt1').val()) || $('#txt1').val()=="0"){
alert("Please Enter Correct value");
}
Now My mandatory things are it should
follow Regex
we should not able to enter the value "0" or "00" or "000"
So my above if() raises an alert if the user enter a "0" and if we enter "00" or "000" or "0000" it doesnot catch it .But if we enter "00000" it catches it due to regex. How can i handle for 2,3,4 zeros .Now Here I can put a regex which doesnot accept zeros such as this one "/^[^0].*$/" but My textfield should Accepts this values as right (0.2,0.3,0.4) .so i cannot use this regex.

Avoid regex, it's a nightmare to get exactly right, and to maintain in the future. Instead, use built-in JS string parsing functionality:
var val = parseFloat($('#txt1').val());
if (isNaN(val) || (val === 0))
{
alert("Please Enter Correct value");
}

/^[1-9]\d{0,3}(?:\.\d)?$|^0\.[1-9]$/
The first alternative matches any number from 1.0 to 9999.9. The first digit has to be at least 1, which eliminates leading zeroes. The fraction part is optional ((?:\.\d)?), so it also matches integers from 1 to 9999. The second alternative handles the special cases of 0.1 through 0.9.

It looks like your regular expression requires 0 through 9999, or 0.0 through 9999.9, but you do not want to accept a 0 alone, or a series of zeros.
If that's the case, I'd say use something similar to ken's answer and process it as a float, then check that the float is above 0 and below 9999.9:
var val = parseFloat($("#txt1").val());
if(isNan(val) || val <= 0 || val > 9999.9) {
alert("Please enter a value between 0 and 9999.9");
}

If you need to use your regex and just add a check that the string doesn't consist entirely of zeroes, you can add a negative lookahead expression: (?!0+$) and enclose the alternation in a non-capturing group:
/^(?!0+$)(?:[0-9][0-9]{0,3}|[0-9][0-9]{0,3}[\.][0-9])$/

No need for Regex or any of that, quite simple.
if(('#txt1').val() < 0.1 ){
alert("Please Enter Correct value");
}
There you go, problem solved

Related

Calculation for comma number gives NaN value

I tried to multiply 2 input where user need to key in the number but the output gives me NaN value.
The input number btw have comma separator. I tried to implement the method from the link below and the comma separator is working. It just that when I multiply them it gives me NaN value.
Can jQuery add commas while user typing numbers?
Can anybody help me with this. Really appreciate your help.
Javascript
$('.textInput').on('change keyup', function() {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/(\d)(?=(\d{3})+$)/g, '$1,');
;
});
product_total_price=0;
var product_price= Number($('#id_Product-0-price').val());
var product_quantity= Number($('#id_Product-0-quantity').val());
product_total_price= product_price * product_quantity;
$('#id_Product-0-total_price').val(product_total_price);
});
The problem here is that you have modified your inputs to show commas, which is totally fine, BUT you didn't remove the commas before casting/converting them to Number.
A quick test of converting a Number from string "1,234" will give you a NaN result. See screenshot:
Solution:
Remove Comma
Then cast to Number
Then compute product_total_price
To remove all commas, simpy use:
yourString.replace(/,/g, '')
Hope this helps!

REGEX to match only VALID EXCEL COLUMNS (A-XFD)

Ok, I have ANOTHER REGEX question for everyone.
I have a field that has multiple validation steps. The first step is to ensure it isn't blank, second is to ensure that only between 1 and 3 CAPITAL LETTERS are entered, and third, to ensure it doesn't contain "[" (an opening bracket will denote a function in this scenario and we skip validation). All of this works. Now, I have to ensure that the value being entered is only a valid Excel Column Reference. Valid Excel Columns can be the letters A - XFD.
I am currently using:
if (checkValue !==""){ //check for not blank
if ((checkValue.match(/^[A-Z]{1,3}$/) === null) && (functionCheck === false) && (validateColumnRange(rangeFrom))) { //check for only 1 - 3 alpha chars & run function check (function looks for "["), and run function check to validate column range
//do A - XFD validation here
}
}
any further direction will be much appreciated as I have been through regex tuts for hours now and am lost.
I had been given help on a similar issue in the past and my poor attempt to emulate the function that was provided then is as follows:
function validateColumnRange(valueRange) {
if (typeof valueRange !== "string" || !valueRange.length)
return false;
var startIndex = valueRange.search(/[\d+]/);
var column = valueRange.substring(0, startIndex).toUpperCase();
return (column >= "A" && column <= "XFD");
}
it doesn't work...please help
Since you've already determined that the value is 1-3 alphabetic characters, how about:
(column.length < 3 || column <= "XFD")
Any value with 2 or less letters should be acceptable, and for the case of three letters, alphabetic comparison is adequate.
Use this regex expression:
/^[A-XFD]+$/

JavaScript praseInt("3e3", 10) gives answer 3

My task to prompt for a number. And loop till its a number
do {
num=prompt ("Please enter a number:");
if (parseInt(num,10)) {
if (typeof num !=="number") {
if (!isNaN(num)) {
stop=1;
}
}
}
} while (stop != 1);
When I enter "3e3" it works. Y?
how do i fix the praseInt("3e3", 10)?
Check it with regular expression such as /^\d+$/.
if (/^\d+$/.test(num)) {
// it's an integer
} else {
// it's not an integer
}
parseInt will take the first characters of the string until it finds one that it's numeric (or reaches the end).
With that in mind, 3e3 reads the first 3 and discards the rest.
That said, your logic is flawed: parseInt returns the number, whereas you seem to be treating it like it were changing it.
That's because parseInt ignores anything after (and including) first invalid character (step 11.)
If you want to reject things like 3e3, then you can simply test whether the string contains decimals only by doing /^\s*\d+\s*$/.test(num).
If you want to process things like 3e3, then you can simply use unary + operator to convert a string to a number, something like +num. (This will accept strings like 4.2e+42 or 0x2A.)

Need a Reg Expression to find a decimal range

I am currently needing a reg expression which will evaluate a decimal range.
The requirements are as below
1) Can allow only 1 or 2 decimal places after dot or can as well allow whole numbers (e.g) 1234 , 123.4, 1245.78 are valid
2) The range should be within 9999 (e.g) 9999.0 , 9998.99 , 9999.00 - Valid | 9999.01,10000.00 - not Valid
3)Do not require leading or trailing zeros
So far i have tried to achieve till writing this reg expression
/^[0-9]\d{1,4}(\.\d{1,2})?$/.test(value);
... but unable to proceed with setting range till digit 9999 (since 9999.01 also not valid )can you help.
Why don't just apply regular expression to determine is your string a valid digit with dots float, then typecast it to Number and find wether it is bigger than 9999 or not.
Regexp for your needs caould be very complex and take too much CPU from client.
Here's something quick and dirty that should work for you: http://regex101.com/r/vK1jM3
/^(?(?=9999)9999(?:\.0+)?|\d{1,4}(?:\.\d{1,2})?)$/gm
I merely handle the special case of 9999
This works as far as I can see:
^(9999(?!\.[1-9])(?!\.0[1-9])\.[0-9]{1,2}|9999|(?!9999)[0-9]{1,4}|(?!9999)[0-9]{1,4}\.[0-9]{1,2})$
Testing it out:
var monstrosity = /^(9999(?!\.[1-9])(?!\.0[1-9])\.[0-9]{1,2}|9999|(?!9999)[0-9]{1,4}|(?!9999)[0-9]{1,4}\.[0-9]{1,2})$/;
console.log(monstrosity.test("9999.00")); // true
console.log(monstrosity.test("9999.01")); // false
console.log(monstrosity.test("9999")); // true
console.log(monstrosity.test("9998.4")); // true
console.log(monstrosity.test("0")); // true
console.log(monstrosity.test("0.5")); // true
If you add something like this to the codebase, future maintenance programmers will hunt you down with pitchforks. Try to solve the range check without regex, as webbandit suggested.
Why a regexp? Just do
x > 0 && x <= 9999 && (x*100 - Math.floor(x*100) == 0)

JavaScript Number preserve leading 0

I have a problem, I build a very simple javascript search for postal codes.
I am using JS Numbers because I want to check if the passed number (search term) is less||equal or more||equal to the max and min.
value >= splitZips[0] && value <= splitZips[1]
But the Javascript Number var type deletes leading 0, which is a problem because I have postal codes like 01075 and also postal codes like 8430. So it can not find the small 4 digit codes.
Any idea how to fix this?
Represent them as a String. Outside of strict mode, a leading zero denotes an octal number otherwise.
Also, why would a leading zero have any significance when calculating numbers? Just use parseInt(num, 10) if you need to.
Store and display the postcodes as strings, thus retaining the leading zeros. If you need to make a numerical comparison convert to number at the time. The easiest way to convert is with the unary plus operator:
var strPC = "01745",
numPC = +strPC;
alert(numPC === +"01745"); // true
+value >= +splitZips[0] && +value <= +splitZips[1];
// etc.
Before you start comparing you might want to ensure the entered value actually is numeric - an easy way to be sure it is a four or five digit code with or without leading zeros is with a regex:
/^\d{4,5}$/.test(searchTerm) // returns true or false
Instead a parseInt you could use type casting :)
"0123">"122" // false
+"0123">"122" // true | that means: 123>"122"
Btw, what more you can use a each of bitwise operators :
~~"0123"
"0123"|0
"0123"&"0123"
"0123">>0
"0123"<<0
With the same effect :)

Categories

Resources