View Full Version : regular expression help
homerUK
02-08-2004, 08:16 PM
Hi,
I have a regular expression that is searched on a field coming from a form....
It basically returns true or false and looks for ONLY numbers.. ie: It validates that the entry is only numbers, and nothing else.
I need it changing so that it will allow a period (.) and a minus (-)
here's what I have at the mo
string.search(/[^\d\s]/)
how do I make it so that only numbers, a full stop and a minus can be entered??
thanks for any help :)
Willy Duitt
02-08-2004, 08:25 PM
I'm still struggling with regular expressions myself.
So forgive me if there is a better way.
string.search(/^[\-+0-9+\.]*$/);
.....Willy
homerUK
02-08-2004, 08:42 PM
hey thanks for the fast response...
i tried
if ((ignoreWhiteSpace && string.search(/^[\-+0-9+\.]*$/) != -1) || (!ignoreWhiteSpace && string.search(/\D/) != -1))
but it still didnt seem to work... it wouldnt allow a "."
not really sure what I am doing!! :p
Willy Duitt
02-08-2004, 09:26 PM
As I said, I'm still struggling.
But I think you are missing either the .match or .test methods.
Here is an example of how I would use it:
<script type="text/javascript">
function isNumber(field){
var regex = /^[\-+0-9+\.]*$/;
if (!regex.test(field.value)){
field.value = field.value.replace(/[^\-+0-9+\.]/g,"");
}
}
</script>
</head>
<body>
<form name="form1">
<input type="text" name="firstnumber" onkeyup="isNumber(this)">
</form>
Perhaps someone who actually knows regex will soon
come along and straighten us both out. Until then....
Hope this is of some help;
.....Willy
Jeff Mott
02-08-2004, 09:34 PM
if (/[^\d.-]/.test(string))
; /* bad */
else
; /*good */Though note that matching this pattern does not mean the string is a number (e.g., "-.-.-" is not a number). Instead use the isNaN function.if (isNaN(string))
; /* not a number */
else
; /* a number */
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.