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 5 of 5
  1. #1
    Regular Coder
    Join Date
    Nov 2002
    Location
    Manchester, UK
    Posts
    533
    Thanks
    4
    Thanked 1 Time in 1 Post

    Question regular expression help

    Hi,

    I have a regular expression that is searched on a field coming from a form....

    It basically returns true or false and looks for ONLY numbers.. ie: It validates that the entry is only numbers, and nothing else.

    I need it changing so that it will allow a period (.) and a minus (-)

    here's what I have at the mo

    string.search(/[^\d\s]/)

    how do I make it so that only numbers, a full stop and a minus can be entered??

    thanks for any help

  • #2
    Banned
    Join Date
    Sep 2003
    Posts
    3,620
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I'm still struggling with regular expressions myself.
    So forgive me if there is a better way.

    string.search(/^[\-+0-9+\.]*$/);

    .....Willy

  • #3
    Regular Coder
    Join Date
    Nov 2002
    Location
    Manchester, UK
    Posts
    533
    Thanks
    4
    Thanked 1 Time in 1 Post
    hey thanks for the fast response...
    i tried

    if ((ignoreWhiteSpace && string.search(/^[\-+0-9+\.]*$/) != -1) || (!ignoreWhiteSpace && string.search(/\D/) != -1))

    but it still didnt seem to work... it wouldnt allow a "."

    not really sure what I am doing!!

  • #4
    Banned
    Join Date
    Sep 2003
    Posts
    3,620
    Thanks
    0
    Thanked 0 Times in 0 Posts
    As I said, I'm still struggling.
    But I think you are missing either the .match or .test methods.

    Here is an example of how I would use it:
    Code:
    <script type="text/javascript">
    function isNumber(field){
      var regex = /^[\-+0-9+\.]*$/;
       if (!regex.test(field.value)){
           field.value = field.value.replace(/[^\-+0-9+\.]/g,"");
       }
     }
    
    </script>
    </head>
    
    <body>
    <form name="form1">
    <input type="text" name="firstnumber" onkeyup="isNumber(this)">
    </form>
    Perhaps someone who actually knows regex will soon
    come along and straighten us both out. Until then....

    Hope this is of some help;
    .....Willy

  • #5
    Regular Coder
    Join Date
    Sep 2003
    Posts
    290
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Code:
    if (/[^\d.-]/.test(string))
        ; /* bad */
    else
        ; /*good */
    Though note that matching this pattern does not mean the string is a number (e.g., "-.-.-" is not a number). Instead use the isNaN function.
    Code:
    if (isNaN(string))
        ; /* not a number */
    else
        ; /* a number */


  •  

    Posting Permissions

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