View Full Version : hwo to use regular expression to verify a string value
jasongr
11-22-2004, 06:34 AM
Hello
I would like to use regular expression to varify on the client side (JavaScript) that a variable starts with a latin letter (a-zA-Z) and then followed by 0 or more latin letters or digits (0-9).
Can someone show me how to do this?
Here are some examples:
Legal values:
- Aaaaa
- Abcde
- A
- A1
- a1a1a1
Illegal values:
- a_2
- 2bbb
- e.b.c
regards
coothead
11-22-2004, 01:59 PM
Hi there jasongr,
this little script may do as you require :)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>string checker</title>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
<style type="text/css">
/*<![CDATA[*/
body {
background:#d4d0c8;
}
div {
width:110px;
padding-top:10px;
border:solid 1px #000;
text-align:center;
background:#ccc;
margin:auto;
}
div input {
width:90px;
margin-bottom:10px;
}
/*//]]>*/
</style>
<script type="text/javascript">
//<![CDATA[
function checkString() {
var pattern=document.forms[0][0].value;
if(pattern=="") {
alert("please pop something in\nthe little box");
document.forms[0].reset();
document.forms[0][0].focus();
}
else {
if((pattern.search(/^\d/)!=-1)||(pattern.search(/\W/)!=-1)||(pattern.search(/[_]/)!=-1)) {
alert("this string is...INCORRECT\nit either starts with a numeral\nor includes excluded characters");
}
else {
alert("this string is OK");
}
}
}
//]]>
</script>
</head>
<body onload="document.forms[0][0].focus()">
<form action="">
<div>
<input type="text"/>
<input type="button"value="check string"onclick="checkString()"/>
<input type="reset"onclick="document.forms[0][0].focus()"/>
</div>
</form>
</body>
</html>
vBulletin® v3.6.7, Copyright ©2000-2009, Jelsoft Enterprises Ltd.