0

I'm using the following code to negate the characters in the regexp. By checking the inverse, I can determine if the value entered is correctly formatted. Essentially, any digit can be allowed but only one decimal point (placed anywhere in the string.) The way I have it now, it catches all numerals, but allows for multiple decimal points (creating invalid floats.) How can I adjust this to catch more than one decimal points (since I only want to allow for one)?

var regex = new RegExp(/[^0-9\.]/g);
        var containsNonNumeric = this.value.match(regex);
        if(containsNonNumeric){
            this.value = this.value.replace(regex,'');
            return false;
        }

UPDATE: Note that I am not trying to get a positive for a valid number, I'm trying for a negative so that I can filter those out. The links to a dup question are seeking the opposite.

dihakz
  • 557
  • 1
  • 15
  • 30
  • Why not match for the positive? `/^[0-9]+(?:\.[0-9]+)?$/` – Niet the Dark Absol Dec 23 '14 at 20:04
  • I want to catch all characters that do *not* fit the bill of a valid float object. The reason for this is so that I can change the user input to ''(null) if they enter a character that is disallowed. – dihakz Dec 23 '14 at 20:08
  • if you use `!` on the positive, you will get the negative ;-) – Lee Taylor Dec 23 '14 at 20:37
  • @LeeTaylor You're suggesting: var regex = new RegExp(/^[0-9]+(?:\.[0-9]+)?$]/); var containsNonNumeric = this.value.match(regex); if(!containsNonNumeric){ this.value = this.value.replace(regex,''); return false; } BUT this allows for ANY character input! – dihakz Dec 23 '14 at 20:41
  • No, I'm referring to the duplicate's answer. If it's not a positive, then it's a negative. – Lee Taylor Dec 23 '14 at 20:46
  • @LeeTaylor No, I'm afraid that does nothing, either. My calculation above works perfectly with the only exception being that I can still enter more than one decimal point. – dihakz Dec 23 '14 at 20:54
  • var text = "1.7x";if(text.match(/^[+-]?\d+(\.\d+)?$/) == null) alert("not a valid float"); – Lee Taylor Dec 23 '14 at 21:03
  • I think there may be some confusion as to what I'm expecting to happen. First, valid input would be any number of numerals with the possibility of only *one* decimal point. The current behavior: The user enters characters one by one, if they are valid characters they will show up. If the character is invalid (e.g. the letter A) the field will replace that character with ''(essentially behaving like a backspace immediately after filling the character in. What I need is the same behavior for the addition of one too many decimal points. – dihakz Dec 23 '14 at 21:15
  • I'd suggest creating a new question and try to put all pertinent information in it this time. Otherwise you're just wasting people's time. – Lee Taylor Dec 23 '14 at 21:55
  • Okay... trying that... hope the SO fairies don't try to kill me. :-) – dihakz Dec 23 '14 at 22:10

0 Answers0