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.
Related
I can't create an input in which the first character entered must be a letter, and the following characters can be only letters or only one underscore in a row
i have an input and following javascript code for it:
var nick = document.getElementById('donate-nickname');
function validatenick(evt) {
var regex = /^[a-zA-Z][a-zA-Z_]*$/;
if(!regex.test(nick.value)) evt.preventDefault();
}
nick.onkeydown = validatenick;
nick.onpaste = validatenick;
but it doesn't work
Some issues:
You are not assigning visited to onkeydown, but instead execute it. (You fixed this after I posted this answer)
input.value will reflect the input as it is before the key was processed, so the validation check comes too early.
The regex does not implement the logic you describe
I would suggest a regex where you perform a negative look-ahead for a double underscore. Also make it allow empty input as else the user cannot delete the last character that remains in the input.
For responding to all input methods, use the input event. Then to cancel the edit that would break the pattern, you could keep track of the most recent input that was still valid, and when there is a violation of the pattern, roll back to that value:
var input = document.getElementById('nickname');
var lastValid = "";
function validate(evt) {
var regex = /^(?!_)(?!.*?__)[A-Za-z_]*$/;
if(!regex.test(input.value)) {
input.value = lastValid;
}
lastValid = input.value;
}
input.oninput = validate;
<input id="nickname">
As a side note, I would personally not block edits like that: users may wrongly think their keyboard is malfunctioning. It is better practice to let the user type what they want, but accompany it with feedback (coloring, an error message, ...).
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.
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
I have a javascript code that allows me to jump automatically from a form field to the next.
It works using fixed lenght fields.
Example: field TIME can be only 4 numbers, so when the user enters the 4th number, the script focuses on the next field.
It works fine, but I would like to add a feature.
I want to use it in a variable lenght field. My field is composed of LASTNAME (space) First letter of FIRSTNAME.
Example: John Doe will be typed as "Doe J"
The only trick I can think of is to make the field shift when space is pressed + another character is entered. This is the only repeating pattern that would allow the function to be executed with any combination of variable lenght lastnames.
So, any idea how to implement it? I am a beginner in js! Here is the original code:
<SCRIPT TYPE="text/javascript">
<!--
var downStrokeField;
function autojump(fieldName,nextFieldName,fakemaxlength)
{
var myForm=document.forms[document.forms.length - 1];
var myField=myForm.elements[fieldName];
myField.nextField=myForm.elements[nextFieldName];
if (myField.maxlength == null)
myField.maxlength=fakemaxlength;
myField.onkeydown=autojump_keyDown;
myField.onkeyup=autojump_keyUp;
}
function autojump_keyDown()
{
this.beforeLength=this.value.length;
downStrokeField=this;
}
function autojump_keyUp()
{
if (
(this == downStrokeField) &&
(this.value.length > this.beforeLength) &&
(this.value.length >= this.maxlength)
)
this.nextField.focus();
downStrokeField=null;
}
//-->
</SCRIPT>
Rather than detecting a space and then a letter, take a look at the string.match() method.
You can do something like name.match(/^[A-Z][a-z]* [A-Z]$/) on keypress to determine if name contains a capital letter followed by any number of lower-case letters followed by a space and another capital letter.
However, be aware that you may run into issues with your criteria, such as someone who has a title like 'Jr', or last names that have spaces, like "Da Silva" or apostrophes, like "O'Malley". Accommodating the many special cases in peoples names can be tricky.
Without using jQuery, what is the best way to limit text entry of a textbox to numbers, lowercase letters and a given set of symbols (for example - and _)? If the user enters an uppercase letter, I would like it to be automatically converted to a lowercase letter, and if the user enters a symbol not within the given set, I would like to be able to instantly show a validation error (show some element adjacent to or below the text box).
What's the cleanest cross-browser way of doing this without the aid of jQuery?
Attach the following to your elements onkeyup event.
function onkeyup()
{
var el = document.getElementById("id"); // or however you want to get it
el.value = el.value.toLowerCase(); // covert to lower case
if (el.value.match(/[^-\d\w]/)) // check for illegal characters
{
// show validation error
...
// remove invalid characters
el.value = el.value.replace(/[^-\d\w]/g, "");
}
else
{
// hide validation error
}
}
The regex matches any character which is not a digit, a letter, a hyphen or an underscore.