I want to validate the data according to day month and year and print the day according to an input value.
class Inputdate extends React.Component {
state={
inputDate:''
}
render() {
console.log(this.state)
return (
<div>
<input
name="date"
type="text"
value={this.state.value}
placeholder="dd-mm-yyyy"
onChange={(e)=> this.setState({inputDate : e.target.value})}
/>
<p>{this.state.inputDate}</p>
</div>
);
}
}
You can do this in multiple ways. I have listed some ways you can validate your date.
function isValidDate(inputDate) {
return !isNaN(Date.parse(inputDate);
}
function isValidDate(inputDate) {
const date_regex = /^(0[1-9]|1\d|2\d|3[01])-(0[1-9]|1[0-2])-(19|20)\d{2}$/;
return date_regex.test(inputDate)
}
function getDay(date) {
const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
if (isValidDate(date)) {
const myDate = new Date(date);
return days[myDate.getDay()];
}
return "Invalid Date"
}
console.log(getDay('12-01-1994'));
console.log(getDay('12-01-0001'));
In your case
function isValidDate(inputDate) {
return !isNaN(Date.parse(inputDate);
}
class Inputdate extends React.Component {
state={
inputDate:''
}
render() {
console.log(this.state)
return (
<div>
<input
name="date"
type="text"
value={this.state.value}
placeholder="dd-mm-yyyy"
onChange={(e)=> {
if(isValidDate(e.target.value)){
this.setState({inputDate : e.target.value.replace('-', '/')})
}
}}
/>
<p>{this.state.inputDate}</p>
</div>
);
}
}