Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Creating a pattern to check against

Status
Not open for further replies.

Markh51

Programmer
May 20, 2003
81
GB
Hi I am having problems trying to create a pattern to check my form fields against.

How do I only allow:
any amount of LETTERS (caps or smalls)
only ONE "-" at a time
only one space at a time.

This is what I have so far:
[^a-zA-Z][ ]{1}[-]{1}

why don't it work ???

Thanks,
Mark
 
Hi Mark,

I wasn't even aware you could do RegExps in JavaScript.. but looking at your expressioin the only thing I can think of is that maybe you'll want to esacpe the '-' character otherwise the compiler might get mixed up and think you are trying to specify a range.

Would something like this work?:
Code:
[^[a-zA-Z]+[ \-]{0,1}]+
 ^    ^   ^  ^  ^     ^
 |    |   |  |  |     |__ 1 or more 'words' of this type
match |   |  |  | 
from  |   |  |  |_____ 0 or 1 space or dash 
start |   |  |  
      |   |  | _____ ' ' or '-'
      |   |
      |   |______ 1 or more of these letters
      |
      |______ any lowercase letter

My regexps are a bit rusty and I'm doing this from memory rather than a book.. so the above might not work! But it might give you an idea of how to do the match differently - which is sometimes what's required.

You could start by escaping the dash (-) with a backslash (\) and seeing if that helps.

Failing that try the Perl/CGI forums as there's some real RegExp'erts there :)

Cheers
Loon
 
Try this:

function tst() {
var tststr = /^\w+[ -]{1,1}+\w+$/;
if(document.form1.testval.value.search(tststr)> -1){
alert("You Entered Valid Data!");}
else { alert("Please Enter Valid Data!");}
}

Good Luck.

2b||!2b
 
<script type=&quot;text/javascript&quot;>

var badChars = /[^a-zA-Z -]/g;

function A(a){
var str = a;
if(str.match(reg)){
alert(&quot;bad char&quot;);
}
if(str.indexOf(&quot; &quot;) != str.lastIndexOf(&quot; &quot;)){
alert(&quot;too many spaces&quot;);
}
if(str.indexOf(&quot;-&quot;) != str.lastIndexOf(&quot;-&quot;)){
alert(&quot;too many dashes&quot;);
}
}
</script>
 
ps the line above should read if(str.match(badChars)) - I changed the var name.
 
yeah, thats what I had. but your expression lets you enter MULTIPLE spaces or &quot;-&quot;, you should only be allowed to enter one at a time, but more than one in a string (just not next to each other)

Cheers.
 
Loon, nice diagram [cheers]

I always get a headache trying to do those [lol]

-pete
 

My first tststr pattern above was allowing numbers,

shoulb be:
var tststr = /^[a-zA-Z]+[ -]{1,1}[a-zA-Z]+$/;

OOOPs....

2b||!2b
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top