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.
Related
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" />
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)
I have a very simple JS code - the goal is to replace a comma with a period in 'real time' (ie. as user is typing in). For example, when user types in: 43,65 then it should be auto-corrected to: 43.65 etc:
<input onkeyup="this.value=this.value.replace(',','.')" type="number">
But it doesn't work (at least in Firefox) - when I enter some number and add a comma, the number disappears completely. And when I type a period, it is removed. So it doesn't work at all as expected...
I also tried:
<input onkeyup="this.value=this.value.replace(/,/g, '.')" type="number">
but it doesn't work either...
It is possible, but only on input type text. input type number does not allow any other symbols than digits.
var input = document.getElementById('input');
function validate(){
input.value = input.value.replace(/,/g, ".");
}
<input onkeyup="validate()" type="text" id='input'>
Try the following code
function numbersOnly(event) {
var key = event.keyCode;
return ((key >= 96 && key <= 105) || (key >= 48 && key <= 57) || key == 188 || key==46 || key==8);
};
<input onkeydown="return numbersOnly(event)" onkeyup="this.value=this.value.replace(',','.')" type="text">
To further explain what's going on here; if a user enters anything other than numbers or decimals into an input of type number <input type="number"> the value will automagically be empty. This is why you cannot operate on input type numbers the way you want. If you want to achieve what you're setting out to do you will need to use an input type text <input type="text"> and write a couple javascript functions to create the desired effect.
function replace(element) {
// set temp value
var tmp = element.value;
// replace everything that's not a number or comma or decimal
tmp = tmp.replace(/[^0-9,.]/g, "");
// replace commas with decimal
tmp = tmp.replace(/,/, ".");
// set element value to new value
element.value = tmp;
}
<input id='numberInput' onkeyup="replace(this)" type="text">
This code should get you started with an input box of type text which will exclude anything other than numbers and decimals, while converting any commas into decimals.
If you would like to keep a counter on the right portion of the input box you will want to add two buttons; incrementer and decrementer, as well as a function which converts the input value of the text input into a double & either increment or decrement the double depending on which button was pressed. If you have trouble with that part I would suggest posting another question.
function to add commas to textboxes:
function Comma1(Num) {
Num += '';
Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', '');
x = Num.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{4})/;
while (rgx.test(x1))
x1 = x1.replace(rgx, '$1' + ',' + '$2');
return x1 + x2;
}
i thinks this helps you
I have a simple input field with type set to number. This will be used to enter input in [0,255] range (for RGB).
<input type="number" id="inputBox" min="0" max="255" step="1" />
In its current form, this input field will accept the following values:
012 // zero prefixed numbers
1.0 // floating-point
.1 // floating-point
-5 // range underflow
300 // range overflow
I want it to accept only the integers in the range of [0,255]. So, no zero prefix, no floating-point numbers.
I've solved the range problem using input event:
inputBox.addEventListener("input", function () {
if (this.validity.rangeUnderflow) {
this.value = this.min;
}
else if (this.validity.rangeOverflow) {
this.value = this.max;
}
});
and floating-point problem using keydown event (by not allowing .):
inputBox.addEventListener("keydown", function (e) {
if (!isFloat(this.step)) {
if (e.key == ".") {
e.preventDefault();
}
}
});
function isFloat(f) {
var f = parseFloat(f);
var floor = Math.floor(f);
var fraction = f - floor;
if (fraction > 0) {
return true;
}
return false;
}
I'm stuck at solving the zero prefixed numbers problem. I can use the following line of code in the input event to remove zero prefix
this.value = this.valueAsNumber; // or parseInt(this.value, 10)
which is working fine, but this kind of breaks the input field's functionality. I can't enter values with E notation. In my case, I don't need to, but I might somewhere else. As soon as I enter 1e, it evaluates to NaN, and is assigned back to input field.
Is there a way to make these both work?
JSFiddle
I just worked on a problem like this. It's super easy to do:
inputBox.addEventListener("keydown", function (e) {
if (!isFloat(this.step)) {
if (e.key == ".") {
e.preventDefault();
}
}
while ( this.value.toString()[0] === "0" && this.value.length > 0){
this.value = this.value.toString().slice(1);
}
});
Note that the value of the field might change in ways other than keydown events, suck as paste. So I would put these checks in a function, validationCheck, and run that function for each relevant event, including the catchall- onchange.
You can use a regular expression such as:
<input type="text" pattern="0|[1-9]\d*">
this will gives you a string representation of a positive whole number without prefixed zeros.
You then have to test with JavaScript if the value is less than or equals 255.
Here is a JSFiddle.
String with only multiple zeros are not accepted.
I have an HTML textbox as:
<input style="width: 13%; height: 25%" name="txthour" id="txthour" onkeypress="return isNumberKey(event)">
I want user to stop if they enter a number greater than 12.
When the user has entered 1, I don't want to them to enter the number 3, this will prevent the number becoming 13 (which is greater than 12).
I am dong this in Javascript as:
function isNumberKey(e) {
if (isNaN($("#txthour").val()))
{
alert("Enter only numbers");
}
if ($("#txthour").val() > 12) {
e.cancel;
}
}
But it's not cancelling the text if it enters 13.
Your first problem with your code is that you are binding it on keypress. That means $("#txthour").val() will not be updated before your event.
You need to know which character the user has pressed. There is a function for that: String.fromCharCode();.
To get the current character, you can use this:
var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
then you need to check if it is a number:
if(!isNaN(currentChar))
Then you need to concatenate that character to your input:
var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition
Parse the new value and check if it's less than or equal to 12. If all of these condition matches, return true.
Final code :
function isNumberKey(e) {
var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
if(!isNaN(currentChar)){
var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition
if(parseInt(nextValue, 10) <= 12) return true;
}
return false;
}
http://jsfiddle.net/6X9Yq/
Edit
To allow the press of the enter key, you need to check if the keycode is 13 :
function isNumberKey(e) {
if(e.keyCode === 13) return true;
var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
if(!isNaN(currentChar)){
var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition
if(parseInt(nextValue, 10) <= 12) return true;
}
return false;
}
Try this instead:
function isNumberKey(e)
{
var exString = $('#txthour').val();
var newString = exString + String.fromCharCode(e.keyCode);
if (isNaN(newString))
{
alert("Enter only numbers");
}
if (newString > 12)
{
e.preventDefault();
}
}
The reason your original code doesn't work is because when the keydown event is called, the value of the text box hasn't been set yet. The code above figures out what the value will be based on your keystroke, and then checks to see if the future value will be > 12. If so, then the preventDefault() call cancels your input.
jQuery solution that:
1) Checks to make sure the user only inputs numbers.
2) Makes sure the number entered is 12 or lower.
3) Alerts the user based on the criteria they're not meeting, and clears the input field.
4) Also accounts for a user pasting something into the field.
$('#txthour').on('paste input', function () {
var number = $(this).val()
if (isNaN(number)) {
alert("Enter only numbers.");
$(this).val('');
}
if (number > 12) {
alert("Value entered must be 12 or lower.");
$(this).val('');
}
});
FIDDLE
$( "#txthour" ).keyup(function() {
if($( "#txthour" ).val() > 12)
{
$( "#txthour" ).val("12");
}
});
http://jsfiddle.net/5tjdL/
The problem:
When the user types a value and you are listening to the onkeypress event, you want to be able to see what the resulting value would be so that you can compare that new value to some other value and then determine if you want to block that input via event.preventDefault() method.
Heres my solution:
1) calculate the "true" new value(now unlike most answers that were previously written that make a huge erroneous assumption "My user will only type a value at the very end of the input field"), I will take into consideration the fact that a user can actually select existing input and overwrite it...ie [before key press] inputField = "12345", user selects "12345" and presses the key for "5", so that would mean that the new value is "5", or if the user selected "234" and pressed the key for "5", the resulting value would be "155".
2) once you have the final "true" value, you can now use the isNaN() method to test if the final value is a valid number or you could just pass the final value to your own method to make whatever comparison you need and decide stop the event by calling event.preventDefault() method. here's a sample code for achieving that.
$(document).keypress(function(event)
{
//this is just a container object for readability purposes
let eventData = {
element: null,
userinput: "",
fieldname: "",
fieldValue: null,
selectionStart: -1,
selectionEnd: -1
}
eventData.fieldName = event.target.id;
eventData.element = document.getElementById(eventData.fieldName);
eventData.fieldValue = element.value; //holds the value before modification
eventData.input = String.fromCharCode(event.keyCode); //what ever the user typed!
eventData.selectionStart = event.target.selectionStart;//this records
eventData.selectionEnd = event.target.selectionEnd;//the user selection if any
let finalValue = getFinalValue(eventData);
if(!isNaN(finalValue)){
//the final value is a number and can be compared to another number!
alert("we have a number! you may proceed");
}else {
//stop right there mister!
alert("You shall not pass!");
event.preventDefault();//user input was blocked!
}
}); // this here marks the end of the onkeypress method,
// and now getFinalValue(eventData) method below...
function getFinalValue(eventData){
let finalValue = eventData.fieldValue.substring(0,eventData.selectionStart) +
eventData.input + eventData.fieldValue.substring(eventData.selectionEnd);
return finalValue;
}//end of the getFinalValue() method