...

View Full Version : Form validation



Loic
08-31-2007, 03:01 AM
Hi, I am fairly new to JavaScript. and I am trying to find a script to validate a field for a survey. More specifically check if a field only has numbers. I found this script on the net, but there is one part of it that I don’t understand…


function checknumber() {
var x=document.checknum.pnum.value
var anum=/(^\d+$)|(^\d+\.\d+$)/
if (anum.test(x))
testresult=true
else{
alert("Please input a valid number!")
testresult=false
}
return (testresult)
}
</script>
<script>
function checkban() {
if (document.layers||document.all||document.getElementById)
return checknumber()
else
return true
}
</script>

What I don’t understand is what this specific part is doing well more how it works… I was wondering if someone could shead some light on my little problem here.. thanks :)

var anum=/(^\d+$)|(^\d+\.\d+$)/

Philip M
08-31-2007, 08:28 AM
var anum=/(^\d+$)|(^\d+\.\d+$)/

This is a regular expression with the pattern to be tested contained between the / characters.

(^\d+$) means one or more digits and nothing but (e.g. 12345 but not A12345)

| or

(^\d+\.\d+$) means one or more digits followed by a decimal point (\.) followed by one or more digits, and nothing but. (e.g. 123.45 but not A123.45).

In short, nothing but a number with or without decimal places is allowed.


You can test your regular expressions at: http://www.ogauge.co.uk/regextester.html



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum