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>
Related
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
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>
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;
}());
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">
I'm trying to find a way to validate a text input on key press, I want to allow numbers only inside my text input including decimals.
I was taking the approach of using jQuery.keydown, and checking what the key was and using.
input numbers max length 999.999
-
my result after . (point) 3 number it is goog. but 99999.999
I need 999.999,222.222,22.01 ->
max length +++.+++
this my code
<input type="text" id="spinEdit2" class="aSpinEdit" />
<script type="text/javascript">
var txt = document.getElementById('spinEdit2');
txt.addEventListener('keyup', myFunc);
function myFunc(e) {
var val = this.value;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?[0-9]?|[0-9])/g;
val = re1.exec(val);
//console.log(val);
if (val) {
this.value = val[0];
} else {
this.value = "";
}
}
</script>
Thanks
How about
/^([0-9]{1,3}(?:\.[0-9]{0,3})?)/g
In case you want the details: the {1,3} means the preceding thing can happen from 1 to 3 times. The (?:) is a non-captured group -- it's a grouping of the following symbols, but it doesn't capture to any variables like $1.