View Full Version : javascript regexp problem

02-22-2012, 05:07 PM
I am trying to get an alert when user type a digit in my textbox and i made this code:

<script type=text/javascript>
function allowed(){
var str=document.getElementById('firstname').value;
var patt=/[0-9]/g;
if(patt.test(str)){alert(not allowed);};
<input type=text id=firstname />
<input type=button value=Submit onclick="allowed();" />

But when i click the button then nothing happen. Please help me. Thanks.

Philip M
02-22-2012, 05:20 PM
<script type = "text/javascript">

function allowed() {
var str=document.getElementById('firstname').value;
if (/[^a-z\'\-]/gi.test(str)) {
alert ("Invalid input - only letters, hyphen and apostrophe are allowed");
document.getElementById('firstname').value = ""; // clear the field
setTimeout("document.getElementById('firstname').focus()", 10); // refocus on it
return false;


<input type=text id= "firstname" />
<input type="button" value="Submit" onclick="return allowed();" />

Remember that a proper name my include a hyphen (Mary-Lou) and/or an apostrophe (O'Hara).

The <!-- and //--> comment (hiding) tags have not been necessary since IE3 (i.e. since September 1997). If you see these in some published script it is a warning that you are looking at ancient and perhaps unreliable code.

"I used to think I was poor. Then they told me I wasn't poor, I was needy. Then they told me it was self-defeating to think of myself as needy. I was deprived. (Oh well, not deprived but rather underprivileged.) Then they told me that underprivileged was overused. I was disadvantaged. I still don't have a dime. But, I have a great vocabulary." - Jules Feiffer, cartoonist.