Strict number input field - javascript

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.

Related

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" />

How do I format my input field using replace regex with javascript and jQuery?

I want to format my <input id="phone_number" type="tel" name="phone_number" maxlength="14"> to have a value like this (123) 456-7890
My current jQuery code:
jQuery("#phone_number").on("keypress", function(event) {
var phoneReg = /[0-9]/g;
var phoneKey = String.fromCharCode(event.keyCode);
if(!phoneReg.test(phoneKey)){
// dont display characters
return false;
} else {
// display numbers only
var phoneNumberVal = jQuery("#phone_number").val();
var phoneNumberUsFormat = phoneNumberVal.replace(/(\d{3})(\d{3})(\d{2})/,"($1) $2-$3");
jQuery("#phone_number").val(phoneNumberUsFormat);
}
});
The code above can format a phone number like this: (123) 456-7890 only after typing all the numbers.
What I want to happen is start adding a parentheses and a dash when the user reaches the 3rd and 6th digit
What I currently tried is this:
jQuery("#phone_number").on("keypress", function(event) {
var phoneReg = /[0-9]/g;
var phoneKey = String.fromCharCode(event.keyCode);
if(!phoneReg.test(phoneKey)){
// dont display characters
return false;
} else {
// display numbers only
if(phoneNumberVal.length < 4) {
newNumber = phoneNumberVal.replace(/(\d{3})/,"($1) ");
jQuery("#phone_number").val(newNumber);
}
}
});
The problem with the updated code above is not being able to detect the 6th digit then automatically add a -
Any help is greatly appreciated. Thanks
I suggest you to follow that process:
If the current input's value is not corresponding to the (XXX) XXX-XXXX format, checks the number of digits only.
If more or exactly 6 (= XXXXXX...), converts to (XXX) XXX- plus the rest if present.
Else if bewteen 3 and 6 (= XXX...), converts to (XXX) plus the rest if present (note the last space in the format I wrote).
Then updates the input's value.
Else if the displayed format is right, just avoid the possibility to type more characters.
The code snippet below (with some bonuses):
$('#telephone').on('keyup', function(e) {
// If not removing a character...
// (Without that check, you'll not be able to remove characters correctly.)
if (e.key !== 'Backspace') {
let value = $(this).val();
// If the value is not corresponding to wanted format...
if (!/\(\d{3}\) \d{3}-\d{4}/.test(value)) {
// Only keeps digits.
value = value.replace(/[^\d]/g, '');
// If we have at least 6 digits, converts the value to "(XXX) XXX-...".
if (value.length >= 6) {
value = `(${value.substring(0, 3)}) ${value.substring(3, 6)}-${value.substring(6)}`;
}
// If we have at least 3 digits (but less than 6), converts the value to "(XXX) ...".
else if (value.length >= 3) {
value = `(${value.substring(0, 3)}) ${value.substring(3)}`;
}
// Updates the input's value.
$(this).val(value);
}
// If the format is correct, just avoid to have too much characters.
else {
$(this).val(value.substring(0, 14));
}
}
});
// Doesn't display unwanted characters.
// (Did this on a different event. Try replacing "input" by "keyup" to see why.)
$('#telephone').on('input', function() {$(this).val($(this).val().replace(/[^\d() -]/g, ''));});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="telephone">
Try something like this after the 6th character?
$("input[name='phone']").keyup(function() {
$(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input name="phone" maxlength="14" />

How to create mask for a float type input in ES6?

The rule of input is simple:
Calculation of student grade ...
The inserted notes must go from 0.0 to 10.0 ...
The user can also enter the "f" character to say that the student was missing ...
I was able to block the characters and use the regex to generate the "POINT".
What are the problems:
Input is not generating the regex correctly, I need to enter 3 characters instead of two for it to insert the point
When entering the character f it should block the digit of numbers and vice versa if it enters a number first
It is letting you enter more than 3 characters in the input, I know this is in the input attribute, however I left it as 3 to be able to insert the point.
Functions:
blockCharactersTwo(_event){
let keyPressed = _event.charCode;
(keyPressed >= 48 && keyPressed <= 57 || keyPressed === 46 || keyPressed === 102) ? null : _event.preventDefault();
}
convertToDecimal(_element){
_element.value = _element.value.replace(/(\d{1})(\d{1,2})$/,"$1.$2") // Insere o PONTO ANTES dos ĂšLTIMOS 2 digitos
}
input and output sample:
1) 80 => 8.0
2) 01 => 0.1
3) number => block caracter "F"
4) "f" => block number
5) "f" => if you type "f" do not enter any more characters and not even "f".
I would do this with a handler for the keydown event, and a separate one for reformatting, to make it easier. The regex /^([fF]{1}|\d{1}\.\d{1}|10\.00?)$/ on regex101.com shows how it works. The allNumbersRe expression just looks for the correct pattern for three numbers.
The trick here is that there is no way to prevent them from entering a value > 10.0, if you want to be able to allow them to enter 100 and format it as 10.0, since the number 100 > 10.0. So, I split the formatting out of the keydown handler and added a blur handler to do the formatting. It also validates that the formatted number is less than or equal to 10.0. Here I'm using HTML5 constraint validation for ease of implementation.
Another thing of note is that I'm using KeyboardEvent.key, which is a relatively new addition to the standard. It will return strings like "Delete" and "Backspace" for keys that produce non-printable characters. In this case, I'm assuming that any keys that do that are okay to allow (you presumably want to be able to delete the value).
document.querySelector('.grade').addEventListener('keydown', function (e) {
const char = e.key;
let newValue = e.target.value;
if (char.length > 1) {
return true;
} else {
newValue += char;
}
const perfectRegex = /^([fF]{1}|\d{1}\.\d{1,2}|10\.00?)$/;
const allNumbersRe = /^(\d{1})(\d{1,2})$/;
const numbersAndDecRe = /^[\d\.]{1,4}$/;
if (!perfectRegex.test(newValue) &&
!allNumbersRe.test(newValue) &&
!numbersAndDecRe.test(newValue) &&
newValue.length > 0) {
e.preventDefault();
}
});
document.querySelector('.grade').addEventListener('blur', function (e) {
const tenRe = /^100$/;
const allNumbersRe = /^(\d{1})(\d{1,2})$/;
const newValue = e.target.value;
e.target.setCustomValidity("");
if (tenRe.test(newValue)) {
e.target.value = "10.0";
} else if (allNumbersRe.test(newValue)) {
e.target.value = newValue.replace(allNumbersRe, "$1.$2");
}
if (parseFloat(e.target.value) > 10.0) {
e.target.setCustomValidity("The value cannot be more than 10.0");
e.preventDefault();
}
});
input:invalid { border-color: red; }
<input type="text" class="grade" maxlength="4">

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.

using Javascript to force number precision on event Onkeypressed in textbox

what i need is to force user while they are typing in a textbox
-
the maximum number they can put is 16
if they press . they can put additional 2 digits after the dots
so what i have done so far is
<asp:TextBox ID="textbox" runat="server" Width="200" onkeypress="validateCurrencyX(this,7, 2);" >0.00</asp:TextBox>
the javascript code is
function validateCurrencyX(sender,prefix, suffix){
var something = document.getElementById('textbox').value;
var valueArr = something.split('.');
if (valueArr[1]!= null && valueArr[1].length > suffix-1)
event.returnValue = false;
if (valueArr[0].length > prefix-1)
event.returnValue = false;
}
anyway my code has problems that
- when i select the whole text, or some part of the text, and press something, it doesn't change anything
is there any ordinary way they do this ? i'm quite new to both javascript and asp.net
thank you for attention
Since you are new to both javascript and .net, it would be best that you not try to reinvent the wheel.
If you are open to using jQuery, take a look at NumberFormatter
$(".amt").blur(function(){
$(this).format({format:"#,###,###,###,###,###.00", locale:"us"});
});
This does what you want it to:
<asp:TextBox ID="textbox" runat="server" Width="200" oninput="validateCurrencyX(this,7, 2);" onkeydown="validateCurrencyX(this,7, 2);" >0.00</asp:TextBox>
JavaScript:
var validateCurrencyX = (function() {
// Closure for local oldVal variable
var oldVal = 0;
return function validateCurrencyX(sender, prefix, suffix) {
setTimeout(function() {
// Convert to number
var val = sender.value * 1,
// Get decimals
dec = sender.value.split('.')[1];
if(
val != val // NaN
|| val > 16
|| val < 0
|| dec && dec.length > suffix // check number of decimals
) {
// If the new input doesn't fit the criteria, revert to the old input.
sender.value = oldVal;
} else {
if(Math.floor(val) != 0 && sender.value.charAt(0) == '0') {
// If it's a number >= 1, remove leading '0's.
sender.value = sender.value.replace(/^0+/, '');
}
// Value is good. Save it in case we need to revert later.
oldVal = sender.value;
}
}, 0);
};
})();
Here's a working example: http://jsfiddle.net/6HUUT/4/
The key to getting a user-friendly real-time text validator is to (1) use onkeydown / oninput not onkeypress because onkeypress doesn't fire for things like paste and delete, and (2) use a setTimeout with interval 0 to check what the user actually inputs and change it after it is updated in the textbox, rather than trying to prevent them from inputting it at the outset. Again, this helps with things like paste and delete, and also inserting characters in places other than the beginning, and generally makes your life easier. The idea is just to let the user make changes, and then check them to make sure they're ok.
Note, the use of onkeydown along with oninput is used for legacy browsers. input is sufficient for modern browsers, but older browsers (circa IE8) don't support it.
This is without using javascript since you have said- is there any ordinary way they do this ? So just have a look at this:
1) the maximum number they can put is 16: for this you have the maxlength property of textbox. Set it to 16
2) This piece of code will restrict your user in entering only 2 digits after the decimal in your textbox.
//In key press event of your TextBox:
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (!char.IsControl(e.KeyChar))
{
TextBox tt = (TextBox)sender;
if (tt.Text.IndexOf('.') > -1 && tt.Text.Substring(tt.Text.IndexOf('.')).Length >= 3)
{
e.Handled = true;
}
}

Categories

Resources