React-imask - How to get access previous value in defenitions to define regex expression for another value in defenitions - javascript

Hello i am using react-imask to create an input that allows masking a timestamp with the format Hh:Mm (like 23:59).
I have set up the mask and can pass a regex for each letter in the definitions parameter, but i want to be able to do a check on the second argument,
Psuedo code:
h: if value of H is 2 then return regex /[0-4]/ else return regex /[0-9]/
h: H.value === 2 ? /[0-4]/ : [0-9]/,
But im having trouble to access this value and i cannot really find any guidance in the documentation for the react-plugin to achieve this, or finding any similar examples where people tried to access a previous value to conditionally apply certain regex based on a condition.
It feels like an ugly solution to use a ref and get the first value from the input like this:
h: inputRef.current.value[0] === 2 ? /[0-4]/ : /[0-9]/,
Is there any better way to achieve what im looking for?
Heres the code for the full component:
<IMaskInput
mask="Hh:Mm"
radix='_'
definitions={{
H: /[0-2]/,
h: /[0-5]/,
M: /[0-6]/,
m: /[0-9]/,
}}
value=""
unmask={true}
onAccept={
(value, mask) => console.log(value)
}
placeholderChar="enter number"
/>

Related

How to replace an input text value in order to match a currency type input

I have a complex problem with a simple input. I want the user to enter an amount of money, so I naturally thought of using a number type. The problem is that I live in Europe and decimals are written with commas(and so the number input will automatically add a comma as separator), but my backend logic expects dots for the cents.
After looking everywhere for alternatives to this problem, I only found I could use a text input and check the user's input with a chain of .replace to test that the user is only entering numbers and eventually a dot followed by only two numbers for the cents.
This is the code we created so far:
export const onChangeCustomInput = (e) => {
let value = e.target.value
value = value
.replace(/[A-Za-z]+$/g, '')
.replace(/,/g, '.')
.replace(/ /g, '')
.replace(/\B(?=(\d{3})+(?!\d))/g, ' ')
.replace(/[.\s]{2,}/, '.')
.split('.')
if (typeof value === 'object' && value.length > 1) {
value[1] = value[1].substr(0, 2)
if (value.length === 3) {
value.splice(2, 1)
}
value = value.join('.')
}
e.target.value = typeof value === 'object' ? value[0] : value
}
this is very heavy (and ugly) code, and Sonar check failed saying this may lead to Denial of Service attack (?...).
Is there a better way to manage this case in vanilla javascript?
Can you try toLocaleString?
Basically if you have a number You can set in which kind of country you're using it.
So, you can show as an EU number, but send to the backend in the other format.
One example:
var number = 35001235.12
number.toLocaleString('en-US') // returns '35,001,235.12'
number.toLocaleString('de-De') // returns '35.001.235,12'
You can read more in: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
You could try using valueAsNumber property of the input element. The value is numeric so it shouldn't matter what was entered by the user. If the input is wrong it takes the value of NaN.
You can use the package Inputmask, it works perfect for your use case, you will use this regex [0-9]*\.[0-9]{2} to match your example
$(document).ready(function(){
Inputmask().mask(document.querySelectorAll("input"));
});
<script src="https://code.jquery.com/jquery-1.10.0.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/jquery.inputmask.js"></script>
<input data-inputmask-regex="[0-9]*\.[0-9]{2}" />

Function not calculating values of formatted numbers

I built a calculator that takes user input (1 text field, 2 select dropdowns) and then displays the output below if the required conditions are met. I also wanted to have the text input field display thousand separators (commas) dynamically as the user types in a number, which I achieved using this:
$('#orderAmt').keyup(function(event) {
// skip for arrow keys
if (event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
});
});
Now, as expected, the calculator function doesn't recognize any of these values because they have been converted to strings. I assume that the next step is to use something like parseInt, so I added this line at the end of the .keyup function:
var converted = parseInt($('#orderAmt'), 10);
But I'm lost on what to do next, because the actual calculator function is written in vanilla JS and here I am trying to store the user's value in a new jQuery variable. Is there a better approach that I should be taking with this?
Here's my JSFiddle - https://jsfiddle.net/bkroger7/yk13wzcc/
If anyone can point me in the right direction it would be greatly appreciated.
BTW - I've tried the infamous, non-jQuery addCommas function as seen here but it won't work for me - only jQuery-based solutions have been working so far.
your problem is you are adding commas to the input field and then taking it as is...
so when you use $('#orderAmt').val() after you add commas you will get 3,000 instead of 3000
what you need to do is just remove the commas...
here is a working fork
https://jsfiddle.net/Lw9cvzn0/1/
notice: var orderAmount = $('#orderAmt').val().replace(new RegExp(','), '');
You're missing the call to .val() to get the field's value. And then you have to remove the commas before you parse it.
var converted = parseInt($('#orderAmt').val().replace(/,/g, ''), 10);

How to substract 2 char in javascript to get a difference in ascii

alert('g' - 'a') is returning Not a Number. ('NAN').
But I expect, to get the difference between ascii as alert(103-97) => alert(6). Hence 6 to be output.
In C, int i = 'g' - 'a', will give i = 6.
How to achieve this subtraction of 2 characters in javascript? (easily without much effort as below)
alert("g".charCodeAt(0) - "a".charCodeAt(0)) is giving 6.
Application : I am using this in chess program.
The only practicable way to do as you want is the way you've already suggested:
alert('g'.charCodeAt(0) - 'a'.charCodeAt(0));
As you know, this will retrieve the ASCII character code from 0th element of the string in each case, and subtract the second from the first.
Unfortunately this is the only way to retrieve the ASCII code of a given character, though using a function would be somewhat simpler, though given the brevity/simplicity of the charCodeAt() solution not all that much so.
References:
String.charCodeAt().
JavaScript doesn't treat characters as numbers; they are single-character strings instead. So the subtract operator will be calculating Number('g') - Number('a').
You should do 'g'.charCodeAt(0) - 'a'.charCodeAt(0) (there is no better way, but you can wrap it in a function)
You can write yourself a custom function. Something like this:
function asciiDif(a,b) {
return a.charCodeAt(0) - b.charCodeAt(0);
}
And then:
alert(asciiDif('g','a'));

Locale independent string search in Javascript

Is there a way for searching / comparing strings without consideration of locale?
I mean: if I have two input sources on my keyboard (Russian and English) and I start typing - I want to search word without consideration what input source is active at the moment.
And I'll find string contained "Search" without metter what I've typed "search" or "ыуфкср"
Thanks.
You would simply need to do search by two phrases: the original input and the result of conversion to another keyboard layout. You would have a conversion map like this:
{
a: 'ф',
s: 'ы',
d: 'в',
f: 'а',
...
}
When I think about it, I come to the conclusion that there is no correct way to implement this, even if we want such opportunity. One reason: there may be different keyboards (when on one keyboard 'a' is equal to 'ф' and on other one it is equal to 'ы'). So probably you should implement such functionllity by your self.

Dynamic Smart date mask while inserting date

Is there a way in javascript or jQuery to detect and change dynamically while typing a date for both a key input and a copy and paste to a text box?
I'm trying to create a functional text box which has two digits such as a month.
Since the month can be a number from 1 - 12 I want to enforce the first digit to be a 1 or a 0.
The trick that I'm trying to do however is when the text box first gains focus and a user beging to type a number, if that number is 2 - 9 I want a zero to automatically fill the first spot and then but the 9 in the second spot.
Before I type anything this date input would look like so:
__/__/_____
If I type a "1"
1_/__/_____
If I type "2" should get
02/__/_____
If I type "22" should get
02/2_/_____
If I type "77" should get
07/07/_____
I would be very interested for in an answer with code or a link to a tool that already does this or a link to a previous post?
Eventually I want to put it in a masked so 7/7/2011 or 7/7/11 or 07/07/2011 will alway fill to 07/07/2011. In the final final version I am trying to get the year to default to the current decade but have a drop down to each 10 year++ --.
Why not attach a listener to the blur of the textbox, rather than to the user's typing.
Think about the user experience if you were typing "1", and all of a sudden, the input started adding or removing zeroes to what you were doing, while you were doing it?
var dayInput = document.getElementById("day-input");
// usually, I'd just use event-listeners, but feel free to refactor
dayInput.onblur = handleDayOrMonth;
function handleDayOrMonth () {
var el = (this === window) ? event.srcElement : this,
number_string = el.value;
// checking that it's an actual number
if (!isNaN(parseInt(number_string)) {
if (number_string.length === 1) { el.value = "0" + number_string; }
}
}
Handling the year would be just the same, except that you'd be adding "20" to the start of whatever it is.
Feel free to jQuery it up.
I believe that the functionality that you want is provided by the jQuery Masked Input plugin
Demo: http://jsfiddle.net/SO_AMK/SEXAj/
Please note that it also only allows numeric characters.
Answer goes here... jQuery masked input plugin.

Categories

Resources