How to validate for Values "0" or "00" or "000" for textfield which has the regex and some accepted values
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 ca开发者_高级运维n 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
精彩评论