Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Sep 2011
    Posts
    50
    Thanks
    4
    Thanked 0 Times in 0 Posts

    javascript regexp problem

    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);};
    }
    //-->
    </script>
    <body>
    <input type=text id=firstname />
    <input type=button value=Submit onclick="allowed();" />
    </body>

    But when i click the button then nothing happen. Please help me. Thanks.
    Last edited by sunnynosid; 02-22-2012 at 05:14 PM.

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,082
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Code:
    <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;
    }
    }
    
    </script>
    
    <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.
    Last edited by Philip M; 02-22-2012 at 05:24 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    sunnynosid (02-22-2012)


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •