Reputation: 306
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.
Upvotes: 6
Views: 13877
Reputation: 99
You can try this:
/([0-9]+[.,]*)+/
It will matche number with or withot coma or dots.
Upvotes: 2
Reputation: 9770
You could also just use the solution from this answer:
parseFloat(text.replace(',',''));
Upvotes: 0
Reputation: 67988
^(?!.*[^0-9.,\n]).*$
Not sure of what you mean by efficient but this fails faster though it takes long to match correct string.See demo.
http://regex101.com/r/aK2zV7/1
Upvotes: 0
Reputation: 19086
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}$/;
Upvotes: 24