I realized a software application management invoicing after having tested my program I noticed the following error:
my table in sqlserver contains: price numeric (6,2)
the user of my program enter price as 555.00 is good.
but when he put 555555 it's error, so I need to specify the mask where the mantissa is optional 0 to 999 and the decimal part is programmable 2 or 3 according to choice of the user, I'm using JQuery Masked input plugin and I have not found good regular expression, please, help, I'm working with jsp / servlet.
You can use jquery numeric for numbers.
The current version does allow what you're looking for but someone has changed the code a little bit and it works:
HTML
<input class="numeric" type="text" />
JQuery
$(".numeric").numeric({ decimal : ".", negative : false, scale: 3 });
This is the whole source.
And I've prepared this fiddle so you can see how it works.
using jQuery input mask plugin (6 whole and 2 decimal places):
HTML:
<input class="mask" type="text" />
jQuery:
$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\.\\d{1,2})?$"});
I hope this helps someone
You can do it using jquery inputmask plugin.
HTML:
<input id="price" type="text">
Javascript:
$('#price').inputmask({
alias: 'numeric',
allowMinus: false,
digits: 2,
max: 999.99
});
https://codepen.io/vladimir-vovk/pen/BgNLgv
Use tow function to solve it ,Very simple and useful:
HTML:
<input class="int-number" type="text" />
<input class="decimal-number" type="text" />
JQuery:
//Integer Number
$(document).on("input", ".int-number", function (e) {
this.value = this.value.replace(/[^0-9]/g, '');
});
//Decimal Number
$(document).on("input", ".decimal-number", function (e) {
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
});
or also
<input type="text" onkeypress="handleNumber(event, '€ {-10,3} $')" placeholder="€ $" size=25>
with
function handleNumber(event, mask) {
/* numeric mask with pre, post, minus sign, dots and comma as decimal separator
{}: positive integer
{10}: positive integer max 10 digit
{,3}: positive float max 3 decimal
{10,3}: positive float max 7 digit and 3 decimal
{null,null}: positive integer
{10,null}: positive integer max 10 digit
{null,3}: positive float max 3 decimal
{-}: positive or negative integer
{-10}: positive or negative integer max 10 digit
{-,3}: positive or negative float max 3 decimal
{-10,3}: positive or negative float max 7 digit and 3 decimal
*/
with (event) {
stopPropagation()
preventDefault()
if (!charCode) return
var c = String.fromCharCode(charCode)
if (c.match(/[^-\d,]/)) return
with (target) {
var txt = value.substring(0, selectionStart) + c + value.substr(selectionEnd)
var pos = selectionStart + 1
}
}
var dot = count(txt, /\./, pos)
txt = txt.replace(/[^-\d,]/g,'')
var mask = mask.match(/^(\D*)\{(-)?(\d*|null)?(?:,(\d+|null))?\}(\D*)$/); if (!mask) return // meglio exception?
var sign = !!mask[2], decimals = +mask[4], integers = Math.max(0, +mask[3] - (decimals || 0))
if (!txt.match('^' + (!sign?'':'-?') + '\\d*' + (!decimals?'':'(,\\d*)?') + '$')) return
txt = txt.split(',')
if (integers && txt[0] && count(txt[0],/\d/) > integers) return
if (decimals && txt[1] && txt[1].length > decimals) return
txt[0] = txt[0].replace(/\B(?=(\d{3})+(?!\d))/g, '.')
with (event.target) {
value = mask[1] + txt.join(',') + mask[5]
selectionStart = selectionEnd = pos + (pos==1 ? mask[1].length : count(value, /\./, pos) - dot)
}
function count(str, c, e) {
e = e || str.length
for (var n=0, i=0; i<e; i+=1) if (str.charAt(i).match(c)) n+=1
return n
}
}
Now that I understand better what you need, here's what I propose. Add a keyup handler for your textbox that checks the textbox contents with this regex ^[0-9]{1,14}\.[0-9]{2}$ and if it doesn't match, make the background red or show a text or whatever you like. Here's the code to put in document.ready
$(document).ready(function() {
$('selectorForTextbox').bind('keyup', function(e) {
if (e.srcElement.value.match(/^[0-9]{1,14}\.[0-9]{2}$/) === null) {
$(this).addClass('invalid');
} else {
$(this).removeClass('invalid');
}
});
});
Here's a JSFiddle of this in action. Also, do the same regex server side and if it doesn't match, the requirements have not been met. You can also do this check the onsubmit event and not let the user submit the page if the regex didn't match.
The reason for not enforcing the mask upon text inserting is that it complicates things a lot, e.g. as I mentioned in the comment, the user cannot begin entering the valid input since the beggining of it is not valid. It is possible though, but I suggest this instead.
Try imaskjs. It has Number, RegExp and other masks. Very simple to extend.
If your system is in English, use #Rick answer:
If your system is in Brazilian Portuguese, use this:
Import:
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.2.6/jquery.inputmask.bundle.min.js"></script>
HTML:
<input class="mask" type="text" />
JS:
$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\,\\d{1,2})?$"});
Its because in Brazilian Portuguese we write "1.000.000,00" and not "1,000,000.00" like in English, so if you use "." the system will not understand a decimal mark.
It is it, I hope that it help someone. I spend a lot of time to understand it.
Related
This is simplified of my code:
$("#annual_sales").on('keyup', function () {
$(this).val( $(this).val().replace(/(\d{3})/g, "$1,") );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
I'm trying to add a comma after every 3 digits.
The patterns works well here, but as you can see (in the code snippet above) it doesn't work in the JS. Any idea what's wrong?
Presumably, you want these commas added from the right as a US-style number separator. This code will do that by reversing before and after adding the commas.
var addCommas = s => s.split('').reverse().join('')
.replace(/(\d{3})/g, '$1,').replace(/\,$/, '')
.split('').reverse().join('') // Really want String.prototype.revese!
$("#annual_sales").on('keyup', function () {
$(this).val( addCommas($(this).val().replace(/\,/g, '')) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
(Doing the reverses by converting to an array really makes me want a String.prototype.reverse method.)
If you have to support numbers with more than two decimal places, there would have to be additional work on this function.
Doesn't work here since the event fire multiple time, then you need to remove the previous added comma's first every time the event fired and add new ones in the desired positions :
$(this).val().replace(/,/g,'').replace(/(\d{3})/g, "$1,")
** NOTE:** I suggest the use of input event instead since it's more efficient when tracking the use inputs, also you could adjust the regex so the comma will not be added at the end of the line :
/(\d{3}(?!$))/g
$("#annual_sales").on('input', function() {
$(this).val($(this).val().replace(/,/g, '').replace(/(\d{3}(?!$))/g, "$1,"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
In your current pattern (\d{3}) you add a comma after matching 3 digits and also when there is already a comma following the 3 digits.
What you might do is match 3 digits using a negative lookahead (?!,) to assert what follows is not a comma:
(\d{3}(?!,))
$("#annual_sales").on('keyup', function() {
$(this).val($(this).val().replace(/(\d{3}(?!,))/g, "$1,"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
If you don't want the comma at the end of the line you could use an alternation in the negative lookahead that asserts what follows is neither a comma or the end of the line (\d{3}(?!,|$))
$("#annual_sales").on('keyup', function() {
$(this).val($(this).val().replace(/(\d{3}(?!,|$))/g, "$1,"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
You need to strip the previously added "," from the value on beforehand like below.
$("#annual_sales").on('keyup', function () {
$(this).val($(this).val().replace(new RegExp(",", "g"), ""));
$(this).val( $(this).val().replace(/(\d{3})/g, "$1,") );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
Honestly, I think the best and most straightforward way to accomplish this is not to rely on directly using regex substitution to add a comma. Because regular expressions run from left to right, and in this case we want to parse from right to left, there's really no easy way to do this.
Instead, I would recommend using javascript to do the heavy lifting:
$("#annual_sales").on('keyup', function () {
var value = $(this).val();
var match = value.match(/[0-9,.$]+/); // Match any chars seen in currency
var new_value = "";
if (match) {
var digits = match[0].match(/\d/g); // Match single digits into an array
if (digits.length > 3) {
for (var i = digits.length - 3; i > 0; i = i - 3) {
// Start at 3 less than the length,
// continue until we reach the beginning,
// step down at intervals of 3
digits.splice(i, 0, ","); // Insert a comma
}
new_value = digits.join("");
$(this).val(new_value);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
With this function, you could expand its handling of currency values, such as prepending the value with a dollar sign, or also splitting on a decimal point and forcing two digits following it.
Edit: Scott's answer is a much shorter version of what I am suggesting here (very nice, by the way).
Well, you coul've just use this simple trick :
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
let label = data.labels[tooltipItem.index];
let value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
return ' ' + label + ' : ' + value.replace(/(.)(?=(.{3})+$)/g,"$1,");
}
}
}
I need a regex for restrict 10 digits before decimal and 2 digits after decimal point. i have tried with this
if (!(/^\d{1,10}(\.$|\.\d{1,2}$|$)/).test(value)) {
event.preventDefault();
event.stopPropagation();
}
<input id="input" type="number" />
It is working fine for input type text.But it is not working for type number.
Working Fiddle
Please help me on this
To restrict Decimal places before and after decimal this should work:
function ValidateDecimalInputs(e) {
var beforeDecimal =3;
var afterDecimal = 2;
$('#'+e.id).on('input', function () {
this.value = this.value
.replace(/[^\d.]/g, '')
.replace(new RegExp("(^[\\d]{" + beforeDecimal + "})[\\d]", "g"), '$1')
.replace(/(\..*)\./g, '$1')
.replace(new RegExp("(\\.[\\d]{" + afterDecimal + "}).", "g"), '$1');
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id = "textBox" onclick="ValidateDecimalInputs(this)"/>
This should work.
if(! (/^[0-9]{10}\.[0-9]{2}$/).test(1234567890.12)) {
}
Just use this regex /^[0-9]{10}\.[0-9]{2}$/ in your code to verify if value is 10 digits before decimal and 2 after.
Parameters
oninput: Detect immediate changes to the input tag.
max: Set the maximum value.
min: Set the minimum value.
type: Set what type of input tag you want.
value: Set the current value.
step: Set the amount to ascend or descend by.
//(function(object){object.value=parseFloat(object.value).toFixed(2);})(this)
//(function(object){var val=object.value;object.value=val.slice(0,val.indexOf('.')+3);})(this)
<input id="input" oninput="(function(object){object.value=parseFloat(object.value).toFixed(2);})(this)" type="number" value="0.00" step="0.01" min="0.00" max="9999999999.99" />
JSFiddle
value= (value.substr(0, value.indexOf(".")) + value.substr(value.indexOf("."), 2));
this will work as it will give all values before "." and only 2 values after "."
This worked for me, even with number type.
JQuery
$("body").on("keyup", ".patternCheck", function(){
if(this.value.match(/^[0-9]{1,10}[.]{1}[0-9]{1,2}$/) == null)
{
$(this).val($(this).attr("pval"));
}
else
{
$(this).attr("pval", $(this).val());
}
});
HTML
<input type="number" value="0.0" pval="0.0" class="patternCheck">
I have an html input type="number" field in an html page. like this:
<input type="number">
To validate the form I need to check that the length of this field is exactly 3. To do this I convert the number to String and execute the length() function.
The problem comes when the number starts with a zero. like 065
In that case the toString() method outputs a 65 with a length of 2
Do you have any idea on how to get the correct length of the number ?
I think that you would have to have your input type as text and then use JavaScript to get the length for validation. After that you could convert it to a number using the Number() function.
Change the input type to text and restrict the input with a pattern and maxlength:
<input type="text" pattern="\d*" maxlength="3">
You can solve this one of two ways:
When the user moves focus away from the field, remove the leading zeroes
In the validation, remove the leading zeroes then check the length
There is no need to convert to a number.
Removing leading zeroes when focus is lost:
function truncateNumericInput(event) {
event = event || window.event;
event.target = event.target || event.srcElement;
if (event.target.nodeName != "INPUT" || event.target.type != "number") {
return;
}
var input = event.target,
value = event.target.value;
input.value = value.indexOf(".") > -1
? value.replace(/^0{2,}/, "0")
: value.replace(/^0+/, "");
}
if (document.addEventListener) {
document.addEventListener("blur", truncateNumericInput, true);
} else {
document.attachEvent("focusout", truncateNumericInput);
}
JSFiddle: http://jsfiddle.net/67jyg1d9/
Removing leading zeroes during validation
var regex = /^0+/;
var value = input.value.replace(regex, "");
console.log(value.length <= 3)
<input type="number" name="quantity" min="0" max="999">
this takes care that only number can be entered and only till 999 that's 3 digits at max
You can solve your problem by using input type as number. You can build your logic by using overflow and underflow as shown below.
<input id="numtest" type="number" min="10" max="20" />
document.getElementById('numtest').validity.rangeOverflow
document.getElementById('numtest').validity.rangeUnderflow
or
document.getElementById('numtest').checkValidity();
rangeUnderflow: return true if value is less then min
rangeOverflow: return true if value is greater than max value.
I have a basic input field in which an amount is to be filled in.
The field is formatted as text as it also has to work with older browser versions.
Is there a way I can use jQuery and/or Regex to set fixed decimals (2) to any number in this field ?
I tried the following but this doesnt change anything:
<input type="text" class="span6" id="amount" maxlength="12" name="amount" />
$('#amount').on('blur', function() {
var amount = $('#amount').val().replace(/^\s+|\s+$/g, '');
if( ($('#amount').val() != '') && (!amount.match(/^\d+$/) ) {
$('#amount').val( amount.toFixed(2) );
}
});
What I am looking for is a way to add two decimals to the input value if there are none and the input is a number.
Examples:
1000 should become 1000.00
1000.99 should stay 1000.99 as there are already two decimals.
Many thanks for any help with this, Tim.
I have created a fiddle, please check Fiddle
before using toFixed convert the amount to integer parseInt(amount).
Edit
Code
$('#amount').on('blur', function() {
var amount = $('#amount').val().replace(/^\s+|\s+$/g, '');
if( ($('#amount').val() != '') && (!amount.match(/^$/) )){
$('#amount').val( parseInt(amount).toFixed(2));
}
});
How to restrict my text field to numbers only and limit them in two with a single function.
Since no one has suggested a regular expression, I will. :-)
var re = /^-?\d{1,2}$/;
if (re.test(input.value)) {
// number is one or two digits with optional leading minus
} else {
// it's not
}
For limiting them to enter only 2 char use maxlength attribute of input. To check enter string is number or not user isNaN(str) function.
<script type="text/javascript">
function ValidateField(FieldName){
// Get fields value
var FieldVal = document.GetElementById(FieldName).value;
// Check it's a number, and then check it's range is correct
// Alternatively you could do FieldVal.length
if(!isNaN(FieldVal) && (FieldVal < 100 && FieldVal > -100))
alert("Valid!");
else
alert("Invalid");
}
</script>
<input type="text" name="MyField" />
<button onclick="ValidateField('MyField')">Test</button>
I've interpreted 'limit to 2' to mean a number ranging from -99 to 99.
In HTML5 you can just use: <input type="number" />
If you are using jquery:
$('#myTextAreaID').keydown(function(event) {
if (event.target.length >1 || event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
});
if you want it to work with the numeric keypad, you will need to also allow keycodes 96 to 105