Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow Only Numbers and a Dot in the following Format with Regex javascript/jquery

I have an input field which should get filled by the user with only numbers and a singel dot/comma and only in the following format.
This should occure .on("input") meaning as the user types it should secure the right input format.

A wrong char should be replaced with a blank.

Format Example:
1.000
1.281
21212.000
21212.810
Nothing like this:
1.02.12
or
1919,201,00
Only a dot between the two Number blocks.

This is what i have so far:

Regex 1:

$("body").on("input", "#testId", function(){
     this.value = this.value.replace(/[^0-9]/g,'');
});

Regex 2:

$("body").on("input", "#testId", function(){
     this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});

Regex 3:

$("body").on("input", "#testId", function(){
     this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});

I think i am doing something wrong with the replace() method. Unfortunately none of them work as i want to. Any help is appreciated.

Here is the FIDDLE

Should Work in IE11

like image 222
TheWandererr Avatar asked Feb 05 '23 18:02

TheWandererr


2 Answers

You can try this. make sure your input type is tel which will allow you to have numeric keypad in mobile browser

const regex = /[^\d.]|\.(?=.*\.)/g;
const subst=``;



$('#testId').keyup(function(){
const str=this.value;
const result = str.replace(regex, subst);
this.value=result;

});
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<body>
<input id="testId" type="tel" />

</body>
</html>
like image 105
Rizwan M.Tuman Avatar answered Feb 07 '23 07:02

Rizwan M.Tuman


try this one,

^[0-9]*(\.|,)?[0-9]*$

this take below cases:

1111, .0000 123,12 12.12 12345

but if you want only

111,11 11.11 12345

so please use this

^[0-9]+(\.|,)?[0-9]+$

to force use dot/comma please use this

^[0-9]+(\.|,)[0-9]+$

add this code

$("#testId").keyup(function(){

   var vals = $("#testId").val(); 

   if(/^[0-9]*(\.|,)?[0-9]*$/g.test(vals))
    $("#testId").val(vals);
     else
    vals = vals.replace(/.$/,"");

    $("#testId").val(vals);
  });

and change input type to

type="text"

like image 26
M. Said Avatar answered Feb 07 '23 06:02

M. Said