Log in

View Full Version : Needed a JS Regular expression



jsnewbie
06-23-2008, 12:08 PM
Hi all,

As a newbie am learning and finding it a bit difficult with the regular expression section in JavaScript. I am looking for a regular expression which checks a string, for finding any characters other than A-Z a-z 0-9 _ and - (plz note that no space characters are allowed).

The following strings are valid in my criteria:


This-is-a-test

This_is_a_test

This_is_a_test_900

9this_is-atest098

The following string are invalid


This is

This*

This_test_$5

I hope you understand my question and help with me with the required regular expression in JavaScript.

Thanks a lot for your help

Regards

Thomas

coothead
06-23-2008, 04:56 PM
Hi there jsnewbie,

and a warm welcome to these forums. ;)

Regular Expressions aren't my forte and someone will probably come up with something a little more precise
but this example, hopefully, should do the job for now...


<!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">
window.onload=function(){

var pattern=/^([a-zA-Z0-9])([a-zA-Z0-9_-]*)([a-zA-Z0-9])$/;

var df=document.forms[0];

df[1].onclick=function(){
if(df[0].value.match(pattern)){
alert('This is a match');
}
else {
alert('This is not a match');
}
}
}
</script>

</head>
<body>

<form action="#">
<div>
<input type="text">
<input type="button" value="check">
</div>
</form>

</body>
</html>

coothead

jsnewbie
06-24-2008, 03:27 AM
Thanks coothead as you said for the time being the one you provided will do the trick.

coothead
06-24-2008, 05:16 AM
No problem, you're welcome. ;)

jsnewbie
06-26-2008, 05:10 AM
Hi coothead,

There is a limitation in your regular expression, it demands at least two characters in a string to find a match with the correct character. In other words if a user wish to have a single letter title then it will make problems.

If you or any other forum user can change the above mentioned regular expression in a manner that a person can enter a single letter title and allows space character also in the title that would be of great help for me.

Thanks

coothead
06-26-2008, 05:24 AM
Hi there jsnewbie,

sorry about that, I missed out an asterisk. :o
Try it like this...


var pattern=/^([a-zA-Z0-9]*)([a-zA-Z0-9_-]*)([a-zA-Z0-9])$/;

coothead