문제

I want regular expression to get rate of interest. I am wanting to accept following things:

Ex:

 0
 0.4
 0.44
 4
44
 4.00
44.00
 4.2
 4.22
44.22

Min 0 and Max 99.99

It must have to accept numeric as well as decimal values but not more than 99.99. Also it should take decimal after first or second digit and after third digit it should display an error message.

I am trying this regular expression but its not perfectly working for me.

$.validator.addMethod('interest', function(value, element) {
    return this.optional(element) || /\d{1,2}\.?\d{0,4}/.test(value);
}, 'Please specify a valid data');

Any help would be appreciated.

도움이 되었습니까?

해결책

A regex to match all of those numbers between 0 and 99.99 would be:

^\d{1,2}(\.\d{1,2})?$

so you're pretty close, but your regex matches 0 to 4 digits after the .

EDIT: forgot ^$

다른 팁

Why mess with regexes if you can simply check for the value:

var input = parseFloat(value)
return !isNaN(input) && input >= 0 && input < 100;

If you want to make sure there are at most 2 decimal placed in the string, the check will be a little longer:

return !isNaN(input) &&
       input >= 0 &&
       input < 100 &&
       !(value.split('.')[1] && value.split('.')[1].length > 2);

If you use regex you will end up having two problems. Try:

function validateStuff(input) {
    return ($.isNumeric(input) && input >= 0 && input <= 99.99);   
}


// Testing:
console.log(validateStuff(5));
console.log(validateStuff("Hello"));
console.log(validateStuff(100));
console.log(validateStuff(99.99));

DEMO

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top