Web Analytics Made Easy -
StatCounter regular expression help - CodingForum

Announcement

Collapse
No announcement yet.

regular expression help

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • 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
    www.mattfacer.com

  • #2
    I'm still struggling with regular expressions myself.
    So forgive me if there is a better way.

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

    .....Willy

    Comment


    • #3
      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!!
      www.mattfacer.com

      Comment


      • #4
        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

        Comment


        • #5
          Code:
          [size=2]if (/[^\d.-]/.test(string))
              ; /* bad */
          else
              ; /*good */[/size]
          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:
          [size=2]if (isNaN(string))
              ; /* not a number */
          else
              ; /* a number */[/size]

          Comment

          Working...
          X