I have an input field of type number and when inserting a decimal place with numpad SEPARATOR key ("." or "Del") nothing happend when pressing it. That's because of localization settings on PC, some languages uses SEPARATOR key like COMMA while others prefer DOT.
Because of type number, input requires only numbers and comma. In this momment need to use regular COMMA key on keyboard that's not very intuitive.
Can I change acting of SEPARATOR key through JavaScript (key event listener) to always be comma, despite language set? How to to define adding comma to value?
If you want the value inside the input field to have a comma instead of dot, you can check the value if it has a dot in it, and if so change the dot to comma.
inputField.onkeyup = checkForDot;
function checkForDot() {
if (inputBox.value.search(/\./) != -1) {
inputBox.value = inputBox.value.replace(/\./, ",")
}
// continue your code
}
Fiddle
Related
I am using input type number and It's preventing character but it's unable to prevent plus, minus symbol or character. But I require to prevent all symbol.
<input type="number">
I have worked on it and create my customise regex and it's working fine but I want to know why it's working like that for input type number and how we can fix that.
You can do this using jquery
$('input').keypress(function (e) {
var txt = String.fromCharCode(e.which);
if (!txt.match(/[0-9]/)) {
return false;
}
});
Because that's exactly how the spec says it should work. The number input can accept floating point numbers, including negative symbols and the e or E character:
A floating-point number consists of the following parts, in exactly
the following order:
Optionally, the first character may be a "-" character.
One or more characters in the range "0—9".
Optionally, the following parts, in exactly the following order:
a "." character
one or more characters in the range "0—9"
Optionally, the following parts, in exactly the following order:
a "e" character or "E" character
optionally, a "-" character or "+" character
One or more characters in the range "0—9".
You can do it with simple and a minimum limit for your number. Something like this:
<input min="0" type="number" step="1">
Now adding + or - signs make field value invalid and step=1 is for when you only need unsigned integers. If you don't need that, simply remove it.
Edit
If you don't want to + and - signs show in the filed, plus don't accept that input, you need to use some js.
Here is the simplest pure js solution I think:
Your html code:
<input min="0: type="number" step="1" onkeypress="removeSigns()" id="my-input">
And now you need to add this little script to your page:
function removeSigns() {
var input = document.getElementById('my-input');
input.value = parseInt(input.value.toString().replace('+', '').replace('-', ''))
This script gets the element that has my-element id, then overwrite its value.
The new value is int version of old value after replacing + and - signs in it with an empty string(removing them from the string in reality).
This solution is good when you only have one input, if you had more number input, you should change the removeStrin to a version that gives input object from this in the onkeypress. But I don't add that version because of simplicity of the solution.
}
I have an input field in which I want to allow only number and 1 comma. How could I make it accept only single comma?
$("#my-field").on("keyup", checkKey);
function checkKey() {
this.value = this.value.replace(/[^0-9,]/g, "");
}
You could do it like this:
function checkKey() {
var clean = this.value.replace(/[^0-9,]/g, "")
.replace(/(,.*?),(.*,)?/, "$1");
// don't move cursor to end if no change
if (clean !== this.value) this.value = clean;
}
// demo
document.querySelector('input').oninput = checkKey;
<input>
This will remove all repeated commas, and everything between them. That is not an issue, since you press one key at a time.
Remarks
This blocking way of input validation is user unfriendly. It is better to colour things, or put messages, than to make the keyboard disfunctional.
Consider using the <input type="number"> element, which has number validation built in.
The input event is often more useful for checking for changes in the input than keyup, since changes can also be made via mouse actions and the context menu.
If you want to allow dot instead of comma, then change every , with \. in the regular expressions, as . has a special meaning in regular expressions, and must be escaped to be taken as a literal character.
I have an input for a phone number in french format
The input accepts two kinds of format, so i can input this:
0699999999
+33699999999
no check is done for the length of the number.
The table in database, the field is of varchar 12, i can have shorter input though.
The constraints: input contains only digits from 0 to 9, optional '+' sign accepted only if it starts the string, not after.
Currently i am in Angular with a directive, in that directive the heart is this expression :
var transformedInput = inputValue.replace(/[^0-9]/g, '');
i want the optional leading '+' sign, how can i achieve this?
thanks.
You could make the plus sign optional:
if (/\+?\d*/.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
subject is the text you want to check. \+ makes the plus sign a literal and the questionmark makes it optional.
If you just want to check wether ther is a plussign drop the questionmark. But if that is your goal don't use a regex. That is too much overhead. Simply get the first charactor of the trimmed string and check for the plus.
Change it to
var transformedInput = inputValue.replace(/[^0-9\+]/g, '').replace(/(.)\+/g, '$1');
Note - this will NOT add a + unless there is already a + in the input
What it does is
Do not remove the + symbol on the first replace
Remove every + symbol that is preceded by some character on the 2nd replace
I'm using the following code to negate the characters in the regexp. By checking the inverse, I can determine if the value entered is correctly formatted. Essentially, any digit can be allowed but only one decimal point (placed anywhere in the string.) The way I have it now, it catches all numerals, but allows for multiple decimal points (creating invalid floats.) How can I adjust this to catch more than one decimal points (since I only want to allow for one)?
var regex = new RegExp(/[^0-9\.]/g);
var containsNonNumeric = this.value.match(regex);
if(containsNonNumeric){
this.value = this.value.replace(regex,'');
return false;
}
Here is what I'm expecting to happen:
First, valid input would be any number of numerals with the possibility of only one decimal point. The current behavior: The user enters characters one by one, if they are valid characters they will show up. If the character is invalid (e.g. the letter A) the field will replace that character with ''(essentially behaving like a backspace immediately after filling the character in. What I need is the same behavior for the addition of one too many decimal points.
As I understand your question the code below might be what you are looking for:
var validatedStr=str.replace(/[^0-9.]|\.(?=.*\.)/g, "");
It replaces all characters other then numbers and dot (.), then it replaces all dots followed by any number of 0-9 characters followed by dot.
EDIT based on first comment - the solution above erases all dots but the last, the author wants to erase all but the first one:
Since JS does not support "look behind", the solution might be to reverse string before regex, then reverse it again or to use this regex:
var counter=0;
var validatedStr=str.replace(/[^0-9.]|\./g, function($0){
if( $0 == "." && !(counter++) ) // dot found and counter is not incremented
return "."; // that means we met first dot and we want to keep it
return ""; // if we find anything else, let's erase it
});
JFTR: counter++ only executes if the first part of condition is true, so it works even for strings beginning with letters
Building upon the original regex from #Jan Legner with a pair of string reversals to work around the look behind behavior. Succeeds at keeping the first decimal point.
Modified with an attempt to cover negatives as well. Can't handle negative signs that are out of place and special cases that should logically return zero.
let keep_first_decimal = function(s) {
return s.toString().split('').reverse().join('').replace(/[^-?0-9.]|\.(?=.*\.)/g, '').split('').reverse().join('') * 1;
};
//filters as expected
console.log(keep_first_decimal("123.45.67"));
console.log(keep_first_decimal(123));
console.log(keep_first_decimal(123.45));
console.log(keep_first_decimal("123"));
console.log(keep_first_decimal("123.45"));
console.log(keep_first_decimal("a1b2c3d.e4f5g"));
console.log(keep_first_decimal("0.123"));
console.log(keep_first_decimal(".123"));
console.log(keep_first_decimal("0.123.45"));
console.log(keep_first_decimal("123."));
console.log(keep_first_decimal("123.0"));
console.log(keep_first_decimal("-123"));
console.log(keep_first_decimal("-123.45.67"));
console.log(keep_first_decimal("a-b123.45.67"));
console.log(keep_first_decimal("-ab123"));
console.log(keep_first_decimal(""));
//NaN, should return zero?
console.log(keep_first_decimal("."));
console.log(keep_first_decimal("-"));
//NaN, can't handle minus sign after first character
console.log(keep_first_decimal("-123.-45.67"));
console.log(keep_first_decimal("123.-45.67"));
console.log(keep_first_decimal("--123"));
console.log(keep_first_decimal("-a-b123"));
How can I test valid numbers in the format of?
Accepted:-
100,000
100,000.00
100,000.0000
10,000,000.00
0.00
10000.000
Not Accept:-
,100,00,.
,.100.00
100.00,00
100..,,
( only allow single dot(decimal point) and multiple commas, but the number should not start or end with comma or dot, there should not be any improper use of comma and dots as shown above) I tried the following java script for it but it couldn’t solve my issue. Can anyone update my function…
function isNumber(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
if (key.length == 0) return;
var regex = /^(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/;
//var regex = /^[0-9.,]+$/;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
Try this :
var numRegex = /^(?:[1-9]\d{0,2}(?:,\d{3})*|0)(?:\.\d+)?$/;
numRegex.test("1,000,000");
numRegex.test("100,000");
numRegex.test("100,000.00");
Try
^(\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+|)$
Expl.: Match one to three digits. Then allow any number of groups with a comma followed by three digits. If no match on previous, try any number of digits (more than one). Then allow optional decimals. Change to
^(\d{1,3}(?:,\d{3})*|\d+)\.\d+$
if decimals are mandatory.
Check out regex101
Regards
Check this : ^((?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?)$
DEMO and Explanation
If I'm not mistaken, the problem is not (only?) with the regex, but rather with the event handler: It's accepting a single character, creating a String from this single character, and then matching that against the regex.
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
will never give you a string. If you must use a character-grabbing event, you'll have to use a global variable to accumulate the string over several keystrokes.
The other alternative is to use a textfield and validate the field content when the cursor leaves the field.
If you need assistance with that, please add information which event is handled by isNumber and what interaction you want to achieve (keystroke handling or text field or whatever else).
EDIT:
You'll have to find out from the keystroke event which field the user is in. Get the text value of that field, and match the regex against the field value, not against the single keystroke.
The tricky thing is the first one, I figure. Either you create an event handler only for the text field you need to validate, or (if there's several fields to validate) you create the handler for a DOM element containing all these fields, and look at event.target (and hopefully the browsers you target are compliant enough to support this), which gives you the DOM element the event was triggered.