How to allow only numbers and format value in javascript - javascript

I would like to know how to validate the text field that allows only numbers and then format the value in javascript.
How to validate the input text by not allowing to paste,ctrl,shift, backspace and del and not allowing special charaters and alphabets,
<input name="samount" type="text" id="samount" class="form-control"
#keyup=${this.formatCurrency}>
formatCurrency(e){
var myinput = e.target.value;
var val = myinput;
val = val.replace(/[^0-9]/g,'');
if(val != "") {
var valArr = val.split('.');
valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
val = valArr.join('.');
}
e.target.value = val;
this.rateValue();
}
Should allow only numbers

Keyup event contains the key typed, make a test on it (if parseInt or dot ...).

*try to update your regex expression and use match function in the if condition to check whether your field values are matching with the regrex.
* every key has it seperate keycode u can validate using that keycode to mention that this key doesn't work on this text field

Easiest way is to delete the input value on keyup when it is not numeric.
$("#myinput").keyup(function(e) {
if($(this).val().match(/^[0-9]+$/))
return;
else
$(this).val('');
});
Alternatively check for e.keyCode and prevent input when it does not match the ranges 48-57 and 96-105(numpad has separate keycodes)

Related

How to give space in between number in input just for displaying?

I want to give space in between number just for displaying like this
I used
phone.addEventListener("keyup", function(){
txt=this.value;
if (txt.length==3 || txt.length==7)
this.value=this.value+" ";
});
but this code is working only for input type text, the problem with this is, the length of the input is not considering as 10.
.
Is there any solution, with which it will be displayed with spaces, the length must be 10, and with type number, and in back-end it should be saved without spaces?
Example solution using the pattern input type with simple regexp that ensures only numbers, correct spacing, and submits only numbers without spaces to the server.
Your code does breaks down if the user inputs spaces themselves, so the JavaScript has been enhanced to ensure the correct format.
Ignore the input of spaces and any input beyond 12 characters by preventing the default behavior (ignore the keystroke):
if ((txt.length == 12 || e.which == 32) & e.which !== 8) e.preventDefault();
(Literally "if 12 characters OR keypress is spacebar AND key is not the backspace key" then ignore the keypress)
Add spaces automatically (as your code did):
if ((txt.length == 3 || txt.length == 7) && e.which !== 8)...
NOTE: in both cases, if the backspace key is pressed, then allow that key to work (keycode 8).
When the form is submitted, remove any spaces from the "phone" input so the server only receives the numbers.
document.getElementById("phone").addEventListener("keydown", function(e) {
const txt = this.value;
// prevent more than 12 characters, ignore the spacebar, allow the backspace
if ((txt.length == 12 || e.which == 32) & e.which !== 8) e.preventDefault();
// add spaces after 3 & 7 characters, allow the backspace
if ((txt.length == 3 || txt.length == 7) && e.which !== 8)
this.value = this.value + " ";
});
// when the form is submitted, remove the spaces
document.forms[0].addEventListener("submit", e => {
e.preventDefault();
const phone = e.target.elements["phone"];
phone.value = phone.value.replaceAll(" ", "");
console.log(phone.value);
//e.submit();
});
<form>
<input id="phone" name="phone" type="pattern" placeholder="### ### ####" pattern="[\d]{3} [\d]{3} [\d]{4}">
<input type="submit">
</form>
You can do a string replace before submitting the string to the backend:
number_str = this.value.replace(" ","");
let number_number = parseInt(number_str);
//backend request stuff
You can also use a hidden input to store the unspaced string and a visible one for the spaced one and just update them both? You would only submit the hidden one.
<input id="phonenumber" type="text" />
<input id="secret-phonenumber" type="hidden" />
It's slightly tricky to decide exactly what the user interface should be. Although they can see the spaces they can't delete them, which if the normal browser editing were allowed they would be able to do.
We also want to ignore non-digit input and not allow the total number of digits to go beyond 10.
This snippet does these things by having the input as type normal text rather than number and testing each key input to see if it should be included or not and rewriting the value each time with the spaces inserted if required.
const phone = document.querySelector('.phone');
phone.addEventListener("keyup", function(e) {
let txt = this.value.replace(/\D/g, '');
let newtxt = '';
//now copy the number inserting a space where needed
for (let i = 0; i < Math.min(txt.length, 10); i++) {
newtxt += txt[i];
if ((i == 2) || (i == 5)) {
newtxt += ' ';
}
}
if (newtxt[newtxt.length - 1] == ' ') newtxt = newtxt.substring(0, newtxt.length - 1);
this.value = newtxt;
});
<input class="phone">
There needs to be further thought as to whether some refinements to the user interface would be a good idea. For example:
re-positioning the cursor (at the moment it goes to the end of the
string after each input which the user maybe won't expect if they are
editing part way along the number)
and it's probably a moot point as to whether it is best to show
briefly a character that is illegal, to sort of reassure the user
they have indeed pressed a key, or whether that character should
never show.
Before submitting the value to the backend, remember to remove the spaces:
phone.value.replace(/\D/g, '');

Allow digits to be replaced in a length-limited field

I am using a Regex to validate a number field. This allows only numbers in the field and the max length is 3 characters. Whenever there are 1 or 2 characters in the field and I select them by double clicking on them I am able to change the number by just pressing any other number.
However when the value contains 3 numbers, which is the max length of the field, when I select the number and try to input other number it doesn't work; I cannot input anything.
I thought this is an issue with the regex, but it's not. The issue is max length.
i tried changing max length whenever it hits the max length and I try to change it it doesn't work.
// Restricting negative numbers and special characters from qyt field and maximum digits to 3
$('.js-bundle-qty').on('keypress', function(event) {
if (event.keyCode != 8) {
console.log('demo');
var regex = new RegExp("^[0-9]{0,3}$");
var inputValue = String.fromCharCode(!event.keyCode ? event.which : event.keyCode);
var key = $(this).val();
key = key + inputValue;
if (!regex.test(key)) {
console.log('enter');
event.preventDefault();
return false;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="js-bundle-qty" max="999">
https://jsfiddle.net/sanket4real/310sgheL/30/
To have the field show only integers and then allow the next pressed integer to force the oldest character from the value, or be replaced by selecting them you can use a regex to replace non-digit characters and slice() within an input event handler, like this:
$('.js-bundle-qty').on('input', function() {
$(this).val((i, v) => v.replace(/[^0-9]/g, '').slice(-3));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="js-bundle-qty" max="999" length="3" />

Field to accept only 5 integers & 2 decimals

I want to add a restriction to the weight field to accept only 5 integers & 2 decimals. I have tried below regex but facing issue with the same.
/^(\d{1,5})(\.\d{1,2})?$/
Field should not accept 6th integer.
Code:
Enter weight:
<input type="text" id="weight" onkeyup="myFunction()">
<script>
function myFunction() {
var x = document.getElementById("weight").value;
var regexp = /^(\d{1,5})(.\d{1,2})?$/g;
var result = x.match(regexp);
alert(result);
}
</script>
You can try something like this:
Explanation:
Keep a variable previousValue to hold last correct value. By default, it will be blank.
Validate input value. If value is incorrect, stop event and set previousValue as input's value.
On valid input, set current value as previous value.
Validation conditions:
Input must have numbers(0-9) and Decimal(.);
Integer part can have max of 5 numbers
Decimal part can have max of 2 numbers
var previousValue = "";
function myFunction(event) {
this.value = this.value || "";
if(validateInput(this.value)){
event.preventDefault();
this.value = previousValue;
}
else{
previousValue = this.value
}
}
function validateInput(value){
var regex = /^[0-9.]*$/;
var valid = regex.test(value);
var parts = value.split(".");
return ( !valid ||
parts.length > 2 ||
parts[0].length > 5 ||
(parts[1] && parts[1].length > 2)
)
}
function registerEvents(){
document.getElementById('weight').addEventListener('keyup', myFunction)
}
registerEvents();
Enter weight:
<input type="tel" id="weight" maxlength="8">
Pointers:
If you have defined max possible length, use maxlength on input to restrict users.
Its better to attach event using addEventListener than adding it in HTML.
Its also better to separate validation and processing logic. Keeps you code clean and maintainable.
Instead of using type="text", use type="tel". This is a minor optimisation for mobiles. It will open number keyboard instead.

What is before and after keydown in Textarea?

I do not want to allow to press the function key like (F1,F2..etc),tabular key and also do not add any characters too.
for that one below code which is not working from my site.
document.getElementById("code").addEventListener("keydown",function(e){
var oldOne = this.value;
var newOne = (this.value + String.fromCharCode(e.keyCode)).toLowerCase();
if(oldOne==newOne){
e.preventDefault();
}
document.getElementById('message').innerHTML = "Is it the same: "+(oldOne==newOne)+", Before: "+oldOne+", After: "+newOne;
})
<textarea id="code"></textarea>
<div id="message"></div>
Because convert charcode that is out of available char range [32, 126] would produce a "", while it seems like a empty string, it accounts to length, and can't be trim like a space, so "apple" + "ctrl"' s length is 6 while it displays as "apple", you should better use
if (e.keyCode < 32 || e.keyCode > 126) {
// This is not a valid char, do something to ignore
}
to ignore those special chars, rather than convert it to string, append to current value then compare with oldValue.
When you're writing
String.fromCharCode(e.keyCode)
Then you're always getting a string even if you press though you're not seeing any change in the value, the String.fromCharCode(e.keyCode) is getting something, the string format of the key, it's not a blank string so you're always getting false in the if.
Either you can check in the keycode or you can check after keyup.
keydown event give you the state of object before your character is written.
`keyup events give you the state of object after it's written.
You may want to do something like this (fiddle):
document.getElementById("ta").addEventListener("keydown", function () {
this.oldValue = this.value;
});
document.getElementById("ta").addEventListener("keyup",function(e){
var oldOne = this.oldValue;
var newOne = this.value;
if(oldOne == newOne){
e.preventDefault();
}
document.getElementById('message').innerHTML = "Is it the same: "+(oldOne==newOne)+", Before: "+oldOne+", After: "+newOne;
})

Allow only numeric input in a text input, and allow a hyphen as an optional first character

I need to automatically clean user entry into a text input - to only allow numbers, except for the first character, which could be a number or a hyphen.
So, for example, if the user types 138a29 it would be automatically updated to 13829.
I was using an onKeyPress event to check the keyCode to allow only numbers, but that's proved to be a little difficult to truly allow only numbers without breaking arrow keys, backspace keys, etc in some browsers. And now there is a new requirement to allow a hyphen(-) as an optional first character, but a hyphen is not valid anywhere else in the string.
I have the Prototype library to use for my particular project, but no jQuery.
The simplest way to do this is to avoid the keyCode and use the textbox's value on keyup. Something like this...
Event.observe('myInput', 'keyup', function(){
var value = this.value, first;
if(value.length == 0)
return;
first = value.charAt(0);
value = value.replace(/[^0-9]/g,'');
if(first == '-')
value = first + value;
this.value = value;
return true;
});
Try this
<script type="text/javascript">
function whatKey(e) {
var thetext = document.getElementById('tt'); // Current value
var theKey = String.fromCharCode(e.keyCode); // key entered
var combval = thetext.value + theKey; // Result would be this
return (!isNaN(combval) || combval=='-'); // if result OK, accept key
}
</script>

Categories

Resources