Reputation: 3579
I am using a input of type number in which it allows multiple decimal points so i have tried using the regex not to allow more than one decimal point but even after using the regex i am facing the same issue can anyone tell me how to allow only one decimal point in input of type number in ionic1
Html:
<input stopccp focus-me class="inputContainer trade_input" type="number" name="" ng-model="vm.total_amount[$index]" ng-change="vm.onTotalCost()" limit-char limit="5" ng-keyup="vm.decimalcheck(vm.total_amount[$index])" >
Regex in function:
function decimalcheck (element) {
$log.log('decimalcheck got called', element);
var regex = /\d*\.?\d?/g;
return regex.exec(element);
}
Upvotes: 6
Views: 8666
Reputation: 41
this work with input field use pattern and event onInput
<input
maxLength={4}
type="text"
pattern="\d+\.?\d?(?!\d)" // [0-9]*\.?[0-9]*
value={unitProgress}
onInput={(e: any) => {
const valueChange = e.target.validity.valid
? e.target.value
: unitProgress;
setUnitProgress(valueChange);
}}
/>
Upvotes: 0
Reputation: 51
Try this in your html, It worked for me
pattern = "^\d*\.?\d+$"
like this:
<input stopccp focus-me class="inputContainer trade_input" type="number" name="" ng-model="vm.total_amount[$index]" ng-change="vm.onTotalCost()" limit-char limit="5" ng-keyup="vm.decimalcheck(vm.total_amount[$index])" pattern="^\d*\.?\d+$">
Upvotes: 0
Reputation: 10360
Try this Regex:
^\d*\.?\d+$
Explanation:
^
- Start of String\d*
- 0+ digits\.?
- 0 or 1 decimal point\d+
- 1+ digits(thus making it mandatory to have atleast one digit after the decimal point, if it is present)$
- End of StringUpvotes: 3
Reputation: 21
I think you just miss start(^) and end($) operator
function decimalcheck (element) {
$log.log('decimalcheck got called', element);
var regex = /^\d*\.?\d?$/g;
return regex.exec(element);
}
Upvotes: 1
Reputation: 310
Script
$('.number').keypress(function(event) {
var $this = $(this);
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((event.which == 46) && (text.indexOf('.') == -1)) {
setTimeout(function() {
if ($this.val().substring($this.val().indexOf('.')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
}
}, 1);
}
if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 1) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 1)) {
event.preventDefault();
}
});
$('.number').bind("paste", function(e) {
var text = e.originalEvent.clipboardData.getData('Text');
if ($.isNumeric(text)) {
if ((text.substring(text.indexOf('.')).length > 3) && (text.indexOf('.') > -1)) {
e.preventDefault();
$(this).val(text.substring(0, text.indexOf('.') + 3));
}
}
else {
e.preventDefault();
}
});
HTML
<input type="text" class="number" />
Upvotes: 1