How to put comma separator in input field in reactjs? - reactjs

i have a form where i show previous field value in input tag. But, as i put type=number. then my .toLocaleString("en-IN") would'nt work.Also, i want to show comma in INR currency styles. i.e 12,25,789
Following is my code:
<Col lg="2">
<Form.Control
size="sm"
// type="number"
value={temp.originalAmount.toLocaleString("en-IN")}
onChange={this.handlechangevalue.bind(
this,
item,
keys,
index
)}
/>
</Col>
P.S been using react-bootstrap

It's not clear for me where you want to use the comma separated values but you can change between styles with the help of regexp and replace. Something like this:
// 1234567 => 12,34,567
const encode = string => string.match(/(\d{2})(\d{2})(\d{3})/).slice(1).join(',');
// 12,34,567 => 1234567
const decode = string => string.replace(/,/g, '');
(If your input is looks like two digits / comma / two digits / comma / three digits but this can be changed easly ofc.)
Then you can convert the result to number before save into the state and the back to the comma version to display the user.
Also, I would use a text type on the input field an a regexp based validator.
I'm using similar in case of dates.

I've come across this before. What you can do is restrict the type of input in your handlechangevalue function to numbers only. If any other character appears then discard/ignore it.
Something like this:
handlechangevalue(e) {
if( parseInt(e.target.value) !== NaN ) {
this.setState({val: e.target.value});
}
}

Related

MUI TextField format input to show numbers and decimals

I'm trying to format the value of the input of this MUI component to show a maximum of 3 numbers following with a maximum of 2 decimals separated by a dot, e.g. 233.99, I want to store this value in a react state called value (const [value, setValue] = useState(0)).
I'm having trouble since I see a lot of approachs to achieve this, but I find it complicated to also keep track if the user already entered the first 3 numbers and not let him enter more while also keeping tack of the decimal values too, since as I said, there should be a maximum of 2 decimals.
I tried regex functions, toFixed js function, and more, but I can't make this work smoothly.
If I understood this correctly, you can achieve this with:
let inp = document.getElementById("input");
inp.addEventListener("keypress", ev => {
ev.preventDefault();
if (!/\d|\./.test(ev.key)) return;
inp.value = /^\d{0,3}(\.\d{0,2})?$/.test(inp.value + ev.key) ? inp.value + ev.key : inp.value;
// update state when value has changed
// if (inp.value != value) setValue(inp.value);
})
<input type="text" id="input">
Alternatively, you can use <input type="text" pattern="^\d{0,3}(\.\d{0,2})?$"> and input.checkValidity() to notify the user on submit.

Antd input to get only numeric data with specific limit

I am using antd component to input only numbers and with a max number as well. My code is as follows:
<Form.Item
name="amount"
rules={[
{
pattern: /^[\d]{0,9}$/,
message: "Value should be less than 999999999",
},
]}
>
<Input
type="number"
onChange={(e) => {
const re = /^[0-9\b]$/;
if ((e.target.value = "" || re.test(e.target.value)))
//use that number
}}
/>
</Form.Item>
However if I input the letter e or -, it does not give me the form Item validation, is the regex I am writing is wrong?
My requirement is to have:
Input box that accepts only numerical digits and no - or e character and with a particular maxLength
This can be achieved by not letting the user type these characters or giving the antd validation msg if either condition fails.
How should I refactor my code to get the desired result? Currently it accepts - digit and does not give any error message. TIA

Svelte - Binding a checkbox to toggle an input value

Using svelte, I want to set the default value of an input based on whether a checkbox is checked or not. The input is used in a drug dosage calculation. The calculation takes an value of weight in kg (k) x the input value.
I also need to have the drug calculation results change when this input value is changed by the checkbox action or when a user changes the input value manually, which doesn't happen currently.
I have been able to implement the input value change when the checkbox is checked but not clear on how to get the calculation to recalculate when the checkbox is checked or the input value is changed manually.
I need some help in integrating the correct input value into my calculation.
Checkbox:
let yes = false;
<input type=checkbox bind:checked={yes} >
Input:
<input value={yes? item.Fdosevalue : item.dosevalue} step={item.dosestep}
min={yes ? item.Fdosemin : item.dosemin} max={yes ? item.Fdosemax : item.dosemax} >
Calculation:
Not sure how to integrate the checkbox change in this calculation.
<span bind:this={k}> {( (k * item.dosevalue)).toFixed(1)} {item.appendvol} </span>
Here is a REPL which will hopefully make it a bit clearer
You can use data binding to accomplish this:
<input bind:value={...} />
You'll just need a place to store the values:
let values = {}
And then you bind to values with a unique key.
<input bind:value={values[item.name]}/>
Make sure to initialize the values dictionary with a default values for each fluid anytime the checkbox changes:
<input type=checkbox bind:value={yes} on:change={handleChange}/>
// initialize default values
function handleChange() {
const entries = fluids.map(item => {
const defaultValue = yes ? item.dosevalue : item.Fdosevalue
return [item.name, defaultValue]
})
values = Object.fromEntries(entries)
}

Convert string to a jsx string in react | How to convert Unicode escape sequences to Unicode characters in react

<Hello name={'\u4ed8\u52a0\u4fa1\u5024\u7a0e# IE9834481A'}></Hello>
class Hello extends Component {
render() {
return (
<div>
{this.props.name}
</div>
);
}
}
The above 2 code snippets are working fine & giving the result as expected, i.e, the escape sequences are getting converted to the relevant unicode characters.
Now consider, there is an array(dynamically populated) and the array values will be the default value for the input tag & this array contains unicode escape sequences.
Ex: <input value={array[i]}></input>
I have tried doing <input value={<Hello name={array[i]}></Hello>}></input>
But the o/p is [object Object].
If I hardcode the string in input tag, o/p is as expected
<input value={<Hello name={'\u4ed8\u52a0\u4fa1\u5024\u7a0e'}></Hello>}></input>
How should I solve this issue, ultimately I want to pre-populate input tag with array value containing unicode escape sequences (after converting to unicode characters).
console.log(JSON.parse('"\u4ed8\u52a0\u4fa1\u5024\u7a0e# IE9834481A"'));
It is not allowed to pass a React Node to the input value. Here is a string expected. If you need the Hi use a function.
const hello = (name) => `Hi ${name}`;
ReactDOM.render(
<input value={hello('\u4ed8\u52a0\u4fa1\u5024\u7a0e')}></input>,
document.getElementById('root')
);

How to validate my input field based on formula

I am trying to validate my input field in a redux form based on a formula.
There are 4 terms in my formula. I would like to restrict the user to type/enter only these 4 terms and make a formula.
TERM1, TERM2, TERM3, TERM4
User can write something in the formula including these 4 terms
TERM1*5,
TERM2/0.2 etc
You can do something like the following.
handleValidate = (text) => {
const re = /(TERM\[1-4])/
return re.test(text)
}
The above function will return true if the text sent to it matches the pattern you specified

Resources