java script to allow valid numbers with comma and dot - javascript

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.

Related

How do i prevent entering in input any character except letters and one underscore in a row?

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 to make avoid user entering numbers for first two chars(but rest all chars must be numbers only) using javascript

I have one requirement in form.My form has textbox field "DEA License number".textbox must allow user to enter alphabet only for first two characters and numbers only after two characters.I want to achieve this functionality using javascript.Note:-I dont want validation but avoid user inputting
Have you tried using regex?
Take a look at this post which has a very similar goal: RegEx pattern any two letters followed by six numbers
Try use some of masked textbox.
For example:
https://css-tricks.com/input-masking/
http://digitalbush.com/projects/masked-input-plugin/
You can easily test this with a regex:
function isValid(str) {
return /^[a-zA-Z]{2}\d+$/.test(str);
}
I am not quite sure what you mean by "I dont want validation but avoid user inputting." If you mean that you don't want the user to be able to type an invalid character, this could theoretically be done with an input event handler:
var oldValue = "";
document.getElementById("test").addEventListener("input", function(e) {
var value = e.target.value;
if ((value.length <= 2 && /^[a-zA-Z]*$/.test(value)) || value.length > 2 && /^[a-zA-Z]{2}\d+$/.test(value)) oldValue = value
else e.target.value = oldValue;
})
However, you'd still need to validate it when it's submitted since the user could've entered an incomplete value.

Input allow numbers and single comma

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.

Forcing Specific Format in Input Field While Typing with Regular Expression

I would like to prevent the use of any other format than formally correct percentages in a field, while any other input would simply not be shown even though a keystroke was executed.
Right now I have the following code which does not allow me to achieve my result:
$("input").keypress(function (e) {
var regex = /\d{1,4}\.?\d{0,3}/g;
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (!regex.test(key)) {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
}
});
While there are many options to validate ex post, e.g. with a button, I would really like to have it on-the-fly, as the user types. However, this expression does not even allow me to insert a decimal point after the first digit(s).
Not a JS dev (comments are welcome!), but right now you are testing your regex against the single key so only digit keys are allowed.
Assuming you want to allow only numbers with 1-4 digits, possibly followed by a . and up to three digits, you can use the regex:
/^\d{1,4}(?:\.\d{0,3})?$/
(?:...) is a non capturing group and ^$ are anchors matching beginning and end of the string. Be aware that this form also allows ending . (like 1234.).
In JS code, this gives (see fiddle here):
var regex = /^\d{1,4}(?:\.\d{0,3})?$/;
$("input").keypress(function (e) {
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (!regex.test($("input").val() + key)) {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
}
});

javascript autojump to next form field

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.

Categories