Reputation: 514
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
Upvotes: 4
Views: 11279
Reputation: 10466
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>
Upvotes: 8
Reputation: 21
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"
Upvotes: 2