Vue3/Javascript - Unable to create an input that only excepts numbers - javascript

I have a project with a input that only excepts numbers.
Inside the template I have defined a input with the value set to the variable that is being changed and the input being set to the function that checks if it is a number:
<input
:value="ie"
#input="(evt) => changeIE(evt)"
type="number"
min="0"
/>
Then in the setup function I have declared a ref ie. This contains the actual value that is being set by the input. I also have declared the `changeIE' function. Here I first get the input text from the evt. Then I check if the last entered character is a number. If not I remove the last character from the string. The next step is to parse the string to an Integer. And lastly I set the value of the variable to the new value of the input.
const ie = ref('');
const changeIE = (evt) => {
let value = 0;
let input = evt.target.value;
let isnum = /^\d+$/.test(input[input.length - 1]);
if (!isnum) input = input.slice(0, -1);
if (input !== '') value = parseInt(input);
ie.value = value;
};
The problem is that the input keeps on excepting non numerical numbers even tough I check if they are numbers and if not I remove that character from the string.

Try to use the v-model with number as modifier and set initial value to 0 :
<input
v-model.number="ie"
type="number"
min="0"
/>
and :
const ie=ref(0)
DEMO

try
const ie = ref(null) // instead of ref('')
By default you set it to a string

Related

How to prevent the input field from accepting more than 2 decimal places in react native?

Restrict input field from accepting more than 2 decimal places. In most of the places, This is recommended, But instead of validating later, I dont want to allow more than 2 decimal places in the input field itself.
var validate = function(e) {
var t = e.value;
e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
}
</script>
</head>
<body>
<p> Enter the number</p>
<input type="text" id="resultText" oninput="validate(this)" />
You could try this.
Set up your state for the input: const [value, setValue] = useState()
Then in your TextInput callback onChangeText, set it up like this.
onChangeText={(text) => {
const validated = text.match(/^(\d*\.{0,1}\d{0,2}$)/)
if (validated) {
setValue(text)
}
}}
This validates a string first to match the following pattern:
zero or more digits
followed by 0 or 1 decimal place
followed by 0, 1, or 2 decimal places (but no more than 2)
I also start the regex with a ^ which forces the match to start at the beginning of the text.
The text argument that is passed in to onChangeText is the entire string (not just the next character). If this string doesn't conform to the regex we set up (validation) then we ignore this value and the state isn't updated.
I'm sure there are other ways to do this, but this one worked for me.
Let me also add this: in React Native's TextInput you can control the keyboard type. Mine is set to a numeric keyboard so the user never gets a chance to enter a letter. This should work either way. It's just a side note
<input pattern='d\+\.\d\d$'/>
You can specify a regex pattern on the input and tell it to only accept numbers (\d), along with a dot and only two numbers after the dot.
I have no idea if that works in react native, only in browsers.
You don't necessarily have to resort to regex.
You can simply use conditionals of substrings on top of regex.
const onChangeText = (text) => {
// Only allow "number & ." input
const cleanNumber = text.replace(/[^0-9.]/g, "")
// Only take first 2 values from split. Ignore the rest.
const strAfterDot = cleanNumber.split('.', 2)[1]
if (strAfterDot.length <= 2){
console.log("setValue now")
setValue(text)
} else {
console.log("Should not be allowed. You can trim the value yourself.)
const strBeforeDot = cleanNumber.split('.', 1)[0]
setValue(strBeforeDot + '.' + strAfterDot.substr(0, 2))
}
}
(Not tested for edge-cases, I'll leave that up to you.)

I cant make inputmask to work with vanilla JS

I would like to use inputmask without jquery loaded and directly in the browser with vanilla JS. But it seems to always require jQuery:
var selector = document.getElementById("gg");
Inputmask({mask:"9999"}).mask(selector);
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/inputmask.min.js"></script>
<input type="text" id="gg">
(Open console and you will see Uncaught ReferenceError: $ is not defined)
Any ideas?
The version you're using (5.x → 5.0.4) is in beta, so it may be broken (it is). You should use the latest stable release, which is 5.0.3 as of now:
var selector = document.getElementById("gg");
Inputmask({mask:"9999"}).mask(selector);
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.0.3/dist/inputmask.min.js"></script>
<input type="text" id="gg">
After searching for it for a while I decided to code my own and it worked perfectly for what I needed:
// Element constants
const maskedInputs = document.querySelectorAll('input[data-mask]')
// Base configuration for all masked inputs
for (const input of maskedInputs) {
// Get the input's mask
let mask = input.getAttribute('data-mask')
// Get the input's mask reverse boolean
const reverse = input.getAttribute('data-mask-reverse') !== null
// Stores a boolean value to indicate if the mask ends with a numeric character
const maskEndsWithNumber = !isNaN(mask.charAt(mask.length - 1))
// If the data-mask-reverse attribute exists, reverse the mask string
if (reverse) {
mask = [...mask].reverse().join('')
}
// Separate the numeric parts from the mask
const numericParts = mask.split(/[^\d]/g).filter(part => !!part.length)
// Add the regex format to all parts
const regexParts = numericParts.map(m => `([\\d#]\{${m.length}\})`)
// Join the regex parts to create the final regex
const maskRegex = new RegExp(regexParts.join(''))
// Calculates the full length of numeric characters
const fullLength = numericParts.join('').length
// Initiates the group counter
let i = 1
// Creates the group mask string
const maskReplace = mask.replace(/\d{1,}/g, () => `\$${i++}`)
// Set the input's max length to the size of the mask
input.setAttribute('maxlength', mask.length)
// Function to handle the input events
function maskHandler(e) {
// Get the input's current value
let { value } = input
// Removes the last character if the user deleted the last non-numeric character
if (e.type === 'keydown' && e.keyCode == 8 && isNaN(value.charAt(value.length - 1))) {
value = value.replace(/\d[^\d]{1,}$/, '')
e.preventDefault()
}
// Removes all non-numeric characters from it
value = value.replace(/[^\d]/g, '')
// Reverse the string if needed
if (reverse) {
value = [...value].reverse().join('')
}
// Fill the string with '#'
value = value.padEnd(fullLength, '#')
// Apply the mask
value = value.replace(maskRegex, maskReplace)
// Get the end of the numeric part (start of the '#' fill)
const fillIndex = value.indexOf('#')
// Checks if the fill character exists
if (fillIndex !== -1) {
// Remove the '#' fill
value = value.slice(0, fillIndex)
}
// Assures the string ends with a numeric character
if (maskEndsWithNumber) {
value = value.replace(/[^\d]$/, '')
}
// Restore the right order of the string
if (reverse) {
value = [...value].reverse().join('')
}
// Update the input's value
input.value = value
}
// Handles the onkeyup, keydown and change events on the masked input
input.addEventListener('keyup', maskHandler)
input.addEventListener('keydown', maskHandler)
input.addEventListener('change', maskHandler)
}
This makes every input element with the "data-mask" attribute have the specified mask applied to it automatically. Another attributed I included was "data-mask-reverse" which is a boolean attribute for when you need the values to fill the mask in reverse (I used it for monetary values):
<!-- Mask example -->
<input type="text" data-mask="9999/9999">
<!-- Reversed mask example -->
<input type="text" data-mask="999,999,999.99" data-mask-reverse>

Prevent invalid formats based on given regex

I have a regex for a set of use cases
Based on that regex I'm trying to prevent the user to type invalid formats.
The regex works and preventing the user adding invalid formats also works.
The part with which I'm struggling now is that if the default value is invalid, the user cannot add additional valid characters.
Here is what I have: http://jsfiddle.net/jgqco7by/2/.
<input id="myInput" type="text" value="co vi1d-" />
var previousValue = document.getElementById('myInput').value;
var pattern = /^[a-zA-Z]+(?:[ -][a-zA-Z]+)*([ ]|[-])?$/g;
function validateInput(event) {
event = event || window.event;
var newValue = event.target.value || '';
if (newValue.match(pattern)) {
// Valid input; update previousValue:
previousValue = newValue;
} else {
// Invalid input; reset field value:
event.target.value = previousValue;
}
}
document.getElementById('myInput').oninput = validateInput;
In this example since I have a default value which contains a number, which is not allowed, everything I type is replaced with previous value because the regex keeps coming back as invalid.
How could I build this so that, if the default value is invalid, the user can still add additional VALID values without having to remove the default invalid values first?
If you want to have the invalid data and a valid one in the same input I'm not seeing how it will happened with your approach.
If you want to have an initial value (that can be either valid or invalid) and then to append something (which is valid) then why are you checking for the initial state.
The third variant is to have both
Empty field and putting a valid chars only
Initial value (valid or invalid) and appending something (valid)
And the result will be to have a valid stuff.
Please place your question / requirement in a more structured manner.
As for the code I would suggest to change your regex. I can give suggestions for modification. :)
For the code:
<input id="myInput" type="text" value="co vi1d-" />
<p id="messageField"></p>
(function() {
const pattern = new RegExp(/^[a-zA-Z]+(?:[ -][a-zA-Z]+)*([ ]|[-])?$/g);
const messageField = document.getElementById('messageField');
function validateInput(event) {
var newValue = event.target.value; // no sense to have a check and to overwrite with window.event , its a different context
messageField.innerText = pattern.test(newValue) ? '' : 'incorrect input'; // its better to use test() method rather than match()
}
document.getElementById('myInput').oninput = validateInput;
}());

In input type text why am i unable to add - using javascript after four letters are typed?

I am just trying to create something like this -
in html i have a input type text and whenever the legth of the value of the input is 2 then javascript will add a hyphen after this like -
if the value id "sd" then javascript will make it "sd-",
its working on console but its not changing the value of the input visually (user cant see).
i want a solution that change the value of the input and i can see that a hyphen added in the input.
let dateA = document.getElementById("dateOne");
dateA.onkeyup = function(){
let dataAValue = this.value;
let dataAValueLength = this.value.length;
if(dataAValueLength == 2) {
let valueReplaced = dataAValue.replace(`${dataAValue}`, `${dataAValue}-`)
// console.log(dataAValue);
dataAValue = valueReplaced;
}
}
<input type="text" id="dateOne">
You are reassigning the variable .You need to modify the object this
You can clean up your code by just using + instead of replace and use ternary operator instead of if-else
let dateA = document.getElementById("dateOne");
dateA.onkeyup = function(){
this.value += this.value.length === 2 ? '-' : ''
}
<input type="text" id="dateOne">

Validate salary input jQuery

I'm trying to validate input value must be like 1.400,00 and 12.000,00.
If input has the correct value, it should remove the disabled class from the else stays disabled.
I tried like this but did't get success :(
<input id="ex2" class="salary" type="number" placeholder="1.400,00 - 12.000,00" name="salaryRange2"/>
Next Step
$("#ex2").on("keyup", function(){
var valid = /^\d{1,6}(?:\.\d{0,2})?$/.test(this.value),
val = this.value;
if(valid){
console.log("Invalid input!");
this.value = val.substring(0, val.length - 1);
$("#checkSalary1").removeClass("disabled");
}
else{
$("#checkSalary1").addClass("disabled");
}
});
Can anyone help how can achieve this condition?
Thanks in advance
Your regex is way out, something like this gets you a little closer:
^\d{1,2}.\d{3},\d{2}$
Which looks for:
1-2 digits
a literal .
3 digits
a literal ,
2 digits
You may like to enhance this to make the decimal portion optional.
From there, you need to actually parse the string to a number to check it is within the valid numerical range (as, for example 95.000,00 would pass on a regex check, but not in the range check.
The number input value is a ... Number, so you can just use a numeric comparison, no RegExp needed. Furthermore, the keyup event will not trigger if you use a mouse to increment or decrement its value.
Here's a snippet that continuously checks the salary input value, enables or disables the button as applicable and shows a message about the input value validity. To make your live even easier, for a [type=number]-input you can also set a minimum and maximum value by the way (used in the snippets checkValue method).
See also
(() => {
const inputElement = document.querySelector("#ex2");
const report = document.querySelector("#report");
const bttn = document.querySelector("button");
const getAction = cando => cando ? "removeAttribute" : "setAttribute";
const checkVal = val => val
&& val >= +inputElement.getAttribute("min")
&& val <= +inputElement.getAttribute("max");
const messages = {
cando: "Ok to submit",
noValue: "Waiting for input (1.400,00 - 12.000,00)",
invalid: "Value should be from 1.400,00 up to 12.000,00"
};
inputElement.focus();
checkValue();
function checkValue() {
const val = inputElement.value;
const cando = checkVal(val);
report.innerHTML = !val
? messages.noValue
: cando
? messages.cando
: messages.invalid;
bttn[getAction(cando)]("disabled", true);
return setTimeout(checkValue, 200);
}
})();
<input id="ex2"
class="salary"
type="number"
min="1400"
max="12000"
step="0.01"
name="salaryRange2"/>
<button disabled>submit</button> <span id="report"></span>

Categories

Resources