Reputation: 6542
I am working on a Java-script, for which I need regular expression to check whether the entered text in text-box should be combination of alphabets and numeric value.
I tried NaN function of java-script but string should be of minimum-size & maximum-size of length 4 and start with Alphabet as first element and remaining 3 element should be numbers.
For example : Regular expression for A123, D456, a564 and not for ( AS23, 1234, HJI1 )
Please suggest me !!!
Code Here:
<script type="text/javascript">
var textcode = document.form1.code.value;
function fourdigitcheck(){
var textcode = document.form1.code.value;
alert("textcode:"+textcode);
var vmatch = /^[a-zA-Z]\d{3}$/.test("textcode");
alert("match:"+vmatch);
}
</script>
<form name="form1">
Enter your Number <input type="text" name="code" id="code" onblur="fourdigitcheck()" />
</form>
Upvotes: 1
Views: 10086
Reputation: 15204
Minimal example:
<html>
<head>
</head>
<body>
<form id="form" name="form" action="#">
<input type="text" onkeyup=
"document.getElementById('s').innerHTML=this.value.match(/^[a-z]\d\d\d$/i)?'Good':'Fail'"
/>
<span id="s">?</span>
</form>
</html>
Upvotes: 0
Reputation: 933
If you want both upper and lower case letters then /^[A-Za-z][0-9]{3}$/
else if letters are upper case then /^[A-Z][0-9]{3}$/
Upvotes: 1
Reputation: 28676
Regexp:
var match = /^[a-zA-Z][0-9]{3}$/.test("A456"); // match is true
var match = /^[a-zA-Z][0-9]{3}$/.test("AB456"); // match is false
http://www.regular-expressions.info/javascriptexample.html - there's an online testing tool where you can check if it works all right.
Upvotes: 3
Reputation: 1918
^[A-Z]{1}\d{3}$
or shorter
^[A-Z]\d{3}$
Description:
// ^[A-Z]\d{3}$
//
// Assert position at the start of the string or after a line break character «^»
// Match a single character in the range between "A" and "Z" «[A-Z]»
// Match a single digit 0..9 «\d{3}»
// Exactly 3 times «{3}»
// Assert position at the end of the string or before a line break character «$»
Test:
/*
A123 -> true
D456 -> true
AS23 -> false
1234 -> false
HJI1 -> false
AB456 -> false
*/
Upvotes: 4