Home > Back-end >  How to validate floating number in [input type=text]
How to validate floating number in [input type=text]

Time:03-18

I need a regular expression which validate the floating point number, I have build the following.

<label for="salary">Enter floating nunmber:</label>
<input type="text" id="salary" name="salary" oninput="this.value = this.value.replace(/[^-0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(/(\-.*)\-/g, '$1');" />

It works but it fails in case of 11-111. How to I fix it.

CodePudding user response:

You can use this this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1') like:

<label for="salary">Enter floating nunmber:</label>
<input type="text" id="salary" name="salary" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1')" />

CodePudding user response:

Maybe something like this:

const validateFloat = (e) => {
    let val = e.currentTarget.value;
    if(isNaN(val)){
        val = val.replace(/[^-0-9\.]/g,'');
        if(val.split('.').length>2) 
             val =val.replace(/\. $/,"");
    }
    e.currentTarget.value = val; 
}

Using:

input.addEventListener("input", validateFloat); 

Working with negative values too.

  • Related