Reputation: 288
An user is able to write data in form of 18/11/2020 [max. 10 chars] in my input. I want, that anything written is directly sanitized dynamically by a method or rule of mine. For instance:
User types a 0 => 00/00/0000 is displayed direct in the label.
For this I have an empty string as default value, but replacing the string with the wanted content didn't work (no changes displayed). Any idea?
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [state, setState] = useState("");
const handleInput = (date) => {
const inputValue = date.target.value;
setState(date.target.value);
const base = new Date(inputValue);
const dateFormatUsEnglish = new Intl.DateTimeFormat("en-US");
const dateFormatGerman = new Intl.DateTimeFormat("de-DE");
const dateParts = dateFormatUsEnglish.formatToParts(base);
const mapped = dateParts.reduce((accumulator, currentValue) => {
accumulator[currentValue.type] = currentValue.value;
return accumulator;
}, {});
if(inputValue === "0"){
//here should be the method replacing the string with the new one
}
if(mapped.month > 12) {
dateParts[0].value = 12; //set max for month
}
if(mapped.day > 31) {
dateParts[2].value = 31; //set max for days
}
if(mapped.year > 2100) {
dateParts[4].value = 2100; //set max for year
}
if((mapped.year % 2) === 0){
} //leapyear
console.log(dateParts); //sliced parts
console.log(inputValue); //user input
console.log(base); //dto
console.log(mapped.month);
console.log(mapped.day);
console.log(mapped.year);
};
return (
<div className="App">
<input onChange={handleInput} defaultValue={state} maxLength="10" />
</div>
);
}
Upvotes: 0
Views: 1313
Reputation: 225
In formattedDate state variable your necessary date format will be assigned and it will be used as a value for your input
const [state, setState] = useState("");
const [formattedDate, setFormatted] = useState("")
const handleInput = (date) => {
//your logic for formatting goes here
setFormatted(`${formatted.month}/${formatted.day}/${formatted.year}`)
};
return (
<div className="App">
<input type="text" onChange={handleInput} defaultValue={state} value={formattedDate} maxLength="10" />
</div>
);
Upvotes: 1