Link to home
Start Free TrialLog in
Avatar of adnan_rais
adnan_rais

asked on

Function for Alpha Numeric letters

Can anybody plz let me know the code in JavaScript that if I need a textfield to allow only alphabetic letters than the function results an error on entering any sort of number in that field. Similarly a textfield allows only numeric values n its function results an 'alert' error on passing any alphabetic letter. Help me getting the whole code plz...
Avatar of hexagon47
hexagon47

<html>
<head>
<title>Form validation</title>
<script>
function validateNbr(){
var value=arguments[0];
var test= /^\d*$/;
if (value.match(test)) {return true} else {return false}
}
function validateAbc(){
var value=arguments[0];
var test= /^\D*$/;
if (value.match(test)) {return true} else {return false}
}
</script>
</head>

<body>
<form>
number
<input name="testfield" type="text">
letter
<input name="testfield2" type="text">
<input type="button" value="TEST NUMBER" onClick="if (validateNbr(this.form.testfield.value)) {alert('OK');} else {alert('not a number!');}">
<input type="button" value="TEST LETTER" onClick="if (validateAbc(this.form.testfield2.value)) {alert('OK');} else {alert('not a letter!');}">
</form>
</body>
</html>  
in the second function I have put var test= /^\D*$/; where \D is everything but a digit, if you want to be more specifici substitute \D with [...] where ... is the charachter you want so [ABCDEF] will match the letters ABCDEF

hope that helped
Here is what I use:
<script language="javascript" type="text/javascript">
<!--
function numbersonly(){
   if (event.keyCode<48||event.keyCode>57)
   return false
}
function alphaonly(){
var val = false;
if ((event.keyCode>=65&&event.keyCode<=90)||(event.keyCode>=97&&event.keyCode<=122)) {
   val = true;
}
return val
}
// -->
</script>

<INPUT id="alphaOnly" onkeypress="return alphaonly();" type="text">
<INPUT id="numbersOnly" onkeypress="return numbersonly();" type="text">
ASKER CERTIFIED SOLUTION
Avatar of Antithesis
Antithesis

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of adnan_rais

ASKER

Thanx very much... your code helped a lot