Forum Moderators: open

Message Too Old, No Replies

regex help

         

syktek

9:05 pm on Jan 29, 2007 (gmt 0)

10+ Year Member



I have a form field that I want to limit to just upper/lower case, numbers, periods, white space, question marks and commas.

Using my code it seems to validate properly if only non-allowable characters exist, as soon as you include allowable and non-allowable content it no longer validates properly. This is my first time using regular expression so I'm sure I'm missing something.

<script type="text/javascript" language="JavaScript">
function checkComment()
{
var validcontent = /[\w\s\.\,\?]/;

if (!validcontent.test(document.getElementById('comment').value)) {
alert("Your Comment field can only contain numbers, letters, periods, question marks and spaces");
document.getElementById('comment').focus();
return false;
} else {
document.getElementById('form1').submit();
}
}
</script>

<form method="POST" action="#" name="form1" >
<textarea cols="20" rows="5" name="comment" id="comment"></textarea>
<input type="button" name="submitBtn" value="send" onClick="checkComment();">
</form>

phranque

12:00 pm on Jan 30, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



the javascript test method checks if (but not only if) a pattern exists within a string.
your logic is working correctly.

what you probably want is something like this:

...
var invalidcontent = /[^\w\s\.\,\?]/;

if (invalidcontent.test(document.getElementById('comment').value)) {
...

the [^...] construct in a regular expression means "not these characters".

syktek

3:35 pm on Jan 30, 2007 (gmt 0)

10+ Year Member



thanks for the reply, i actually got it worked out with this:

var validcontent = /^[\w\s\.\,\?]+$/;