Solved

# Help with Numeric Validation Variation

Posted on 2004-11-21
188 Views
I use the following code to check for numeric value in fields. It does not check for symbols like \$ , ' " etc... Can someone help me out with a reg expression that I can add to this simple method so the field can only contain numbers? One note. decimal point must be allowed. I know there are other methods like making an array of numbers and symbolds and looping through but I don't wish to use it if possible.

<script language=javascript>
function checkval() {
var x, r, ri;
x  = document.myform;
ri = /[A-Z]/i;

r  = x.myfield.value.search(ri);
if (r != -1) {
alert ('this field must be numeric');
return false;
}
return true;
}
</script>
0
Question by:Bob-Villa

LVL 25

Expert Comment

<INPUT type="text" name="numeric" onkeyup='this.onchange();' onchange='this.value=this.value.replace(/[^\d]*/gi,"");' />
0

LVL 31

Accepted Solution

<script language=javascript>
function checkval() {
r  = x.myfield.value
if (isNaN(r)) {
alert ('this field must be numeric');
return false;
}
return true;
}
</script>

or

<script language=javascript>
function checkval() {
r  = x.myfield.value
if (/\D/.test(r)) {
alert ('this field must be numeric');
return false;
}
return true;
}
</script>
0

LVL 1

Author Comment

if (isNaN(r)) worked like a charm.
0

LVL 31

Expert Comment

archrajan, try pasting non-numbers, blurring and then pasting again.
0

LVL 31

Expert Comment

this does work though

<INPUT type="text" name="numeric" onkeyup='this.onblur();' onblur='this.value=this.value.replace(/[^\d]*/gi,"");' >
0

## Featured Post

### Suggested Solutions

Both jQuery and Mootools offer some nice, easy to use scripts. Mootools is best known for their interactive slideshows and jQuery for their menus, but both have many other uses as well.   jQuery is basically a toolkit with many DOM (http://en.wik…
In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…