Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for a valid numeric with optional commas & dot

i am trying only to allow numerals and special chars like '.' and ',' to be allowed in my text string. for that i have tried following code

var pattern = /[A-Za-z]/g;
var nospecial=/[\(#\$\%_+~=*!|\":<>[\]{}`\\)';@&?$]/g;
if (!ev.ctrlKey && charCode!=9 && charCode!=8 && charCode!=36 && charCode!=37 && charCode!=38 && (charCode!=39 || (charCode==39 && text=="'")) && charCode!=40) {
    console.log(text);
    if (!pattern.test(text) && !nospecial.test(text)) {
        console.log('if');
        return true;
    } else {
        console.log('else');
        return false;
    }
}

but not getting the desired output. tell me where i am wrong.

like image 285
Garry Avatar asked Apr 17 '13 12:04

Garry


3 Answers

Forget trying to blacklist, just do this to allow what you want:

var pattern = /^[0-9.,]*$/;

Edit: Also, rather than just checking for numbers, commas, and dots. I'm assuming something like this do even more than you were hoping for:

var pattern = /^(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;

Demo

enter image description here

like image 76
Dallas Avatar answered Nov 07 '22 18:11

Dallas


So why don't you try /^[0-9,.]*$/ instead of negating the test?

like image 5
Dio F Avatar answered Nov 07 '22 18:11

Dio F


You can try this:

/([0-9]+[.,]*)+/

It will matche number with or withot coma or dots.

like image 2
Kumar Gaurish Avatar answered Nov 07 '22 17:11

Kumar Gaurish