PDA

View Full Version : help with regular expression-testing white space and/or alphanumeric characters


htmlcssnewbie
02-05-2008, 09:03 AM
I'm jusing javascript, here. I want to test a string for white space and/or alphanumeric characters. Here are some strings that should test successfully, to give a better understanding of what I'm asking for:

ABC
ABC123
A1B1C1
ABC 123
A1 B1 C1


These should not test successfully:
ABC%*&^
ABC123$%@!
!@#&
!&$ $^+!@
% ^&
AB# $C@

So, I need some way of combining [0-9a-zA-Z] and \s to meet the requirements above. Is there a way i can do this all in one shot, or do I have to split the test string into an array???

coothead
02-05-2008, 01:52 PM
Hi there htmlcssnewbie,

have a look at this example, it may suit your requirements...

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script type="text/javascript">

var df;
var regE=/[^a-z0-9\s]/gi;

window.onload=function(){
df=document.forms[0];
df[0].focus();
df.onsubmit=function() {
return checkInput();
}
}

function checkInput() {
if((df[0].value.match(regE))||(df[0].value=='')){
alert('only white space and/or alphanumeric characters are allowed');
df.reset();
df[0].focus();
return false;
}
else {
return true;
}
}

</script>

</head>
<body>

<form action="http://www.google.com/" method="get">
<div>
<input type="text" name="test"><label> : alphanumeric characters and whitespace only</label><br>
<input type="submit">
</div>
</form>

</body>
</html>

htmlcssnewbie
02-08-2008, 03:19 PM
I tried the above, but it didn't seem to work. So, I used a pattern similar to the one above, split the string using regular expressions, and then did a test on the separated strings. Thanks for the help.

coothead
02-08-2008, 04:58 PM
Hi there htmlcssnewbie,
I tried the above, but it didn't seem to work.
Well, it accepted all these....

ABC
ABC123
A1B1C1
ABC 123
A1 B1 C1

...and rejected all these...

ABC%*&^
ABC123$%@!
!@#&
!&$ $^+!@
% ^&
AB# $C@

...so were does it fail your criteria?