views:

61

answers:

6

Hello,

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>
+3  A: 

This website will tell you exactly what you need to know.

Skilldrick
+2  A: 

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.

MartyIX
Are you sure `/[a-zA-Z][0-9]{3}/.test("AB456")` is false?
KennyTM
KennyTM .. you have right, its true because its match "B456"
Floyd
Sorry for that! This version should be all right.
MartyIX
Sorry dear, it is not working !!!
Rahul Patil
I don't know if your comment was before update or after.
MartyIX
A: 

/[A-Z][0-9]{3}/

alxx
+4  A: 
^[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
*/
Floyd
he doesn't say anything about first letter being capital (though all examples do): `/^[a-z]\d{3}$/i`
Amarghosh
Sorry dear, it is not working !!!
Rahul Patil
@Rahul _dear_, the regex is correct - post the code that you're using to test it.
Amarghosh
@Amaraghosh: he doesn't say that not. all exampels he post are capital.
Floyd
A: 

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}$/

Alex
A: 

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>

Regards

rbo

rubber boots