简体   繁体   中英

JavaScript Regex: How to let only 2 decimal floating number through oninput pattern match?

I have an input type="text" with an input event handler attached to it, which i would like to use to overwrite the input.value with a "filtered" result of the users' key presses.

Basically i want to write a regular expression that only allows floating numbers (positive or negative) with (optionally) 2 decimal positions.

Here's a scripted example of what i'm looking for.

If you hit any key while focusing the input in the example above, the input value will be filtered using a combination of regex and JavaScript.

My test input currently looks like this:

<input type="text" id="test" value="-3c.fvbnj23.79.8fbak-cfb436.sdafosd8r32798s.hdf-5kasjfds-gf..">

The input event handler looks like this:

document.getElementById('test').oninput = function(){
  var foundDot = false,
      str = '';

  this.value.replace(/^-|\.(?=\d)|\d*/g, function(match){
    if (match === '.' && foundDot === true) {
      return;
    }

    if (match === '.' && foundDot === false) foundDot = true;

    str += match;
  });

  this.value = parseFloat(str).toFixed(2);
}

Is it possible to obtain the same result with a regular expressions only?

Even better, it can be done without regex at all.

Well, okay, one regex. I misunderstood that you wanted to preserve digits within non-numeric strings.

All right, fiiiiine, two regexes. ¯\\_(ツ)_/¯

 //oninput is too aggressive, it runs on every keystroke making it difficult to type in longer values. document.getElementById('test').onchange = function(){ // strip non-numeric characters. // First char can be -, 0-9, or . // Others can only be 0-9 or . var val = this.value.replace(/(?!^[\\-\\d\\.])[^\\d\\.]/g,''); // strip out extra dots. Here I admit regex defeat and resort to slice-and-dice: var firstDot = this.value.indexOf('.'); if (firstDot > -1) { val = val.substr(0,firstDot+1) + val.substring(firstDot+1).replace(/\\./g,'') } console.log(val); // Finally the easy part: set the precision this.value = parseFloat(val).toFixed(2); } 
 <input id="test"> 

I don't know why you can't just use a find/replace on each keystroke.

Find ^([-+]?(?:\\d+(?:\\.\\d{0,2})?|\\.\\d{0,2})?)
Replace $1

Expanded

  ^ 
 (                             # (1 start)
      [-+]? 
      (?:
           \d+ 
           (?:
                \. \d{0,2} 
           )?
        |  
           \. \d{0,2} 
      )?
 )                             # (1 end)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM