Hemadri Dasari
Hemadri Dasari

Reputation: 33994

Material-UI Datepicker can't display error/required messages

I am trying to show a validation error message on Date picker like how we do for TextField using errorText and errorStyle props but the validation error message is not working for DatePicker.

I am using material-ui version "^0.18.7".

Please find full functionality below. I am not sure exactly how to implement this. I also understand that the errorText and errorStyle is not a valid prop to DatePicker. Thought it will work for datepicker but it is not. Is there a way to achieve this.

import DatePicker from 'material-ui/DatePicker';

constructor(props){
   super(props)
   const dateYesterday = new Date();
   dateYesterday.setDate(dateYesterday.getDate() - 1);
   this.state={
      dob: null,
      dobError: '',
      dateYesterday: dateYesterday
   }
   this.changeDateOfBirth = this.changeDateOfBirth.bind(this)
}

changeDateOfBirth = (evt, date) => {
if(date == null || date == undefined){
  this.setState({
    dobError: 'Please select your date of birth'
  });
}else{
  this.setState({
    dobError: '',
    dob: date
  });
}
}
const errorStyle = {
    display: 'table'
}

<DatePicker 
    dialogContainerStyle={{position: 'absolute'}} 
    errorText={this.state.dobError} 
    errorStyle={errorStyle} 
    inputStyle={myTheme.inputStyleText} 
    underlineStyle={myTheme.underlineStyle} 
    underlineFocusStyle={myTheme.underlineStyle} 
    floatingLabelStyle={myTheme.floatingLabelStyle} 
    floatingLabelText="Date Of Birth" 
    hintText="Select Date Of Birth" 
    container="inline" 
    locale="en-US" 
    firstDayOfWeek={0} 
    autoOk={true} 
    value={this.state.dob} 
    onChange={this.changeDateOfBirth} 
    defaultDate={this.state.dateYesterday}
 >
 </DatePicker>

Please suggest.

Upvotes: 3

Views: 22394

Answers (1)

Jules Dupont
Jules Dupont

Reputation: 7567

The DatePicker spreads props through to children elements, so you can in fact use the errorText and errorStyle props from the TextField element. For example, I tested the following DatePicker in "^0.18.7" and can confirm it shows up with a red error message:

<DatePicker hintText="Portrait Dialog" errorText="This is an error message." />

You should be aware that the onChange callback in the DatePicker is only fired when a date is selected, so the date argument will never be null or undefined. In other words, you'll never enter into the following if statement:

if(date == null || date == undefined){
  this.setState({
    dobError: 'Please select your date of birth'
  });
}

If you want to check for cases in which the user has not set any kind of date, consider just checking whether or not your DOB is null (I left out the irrelevant props to keep things short):

<DatePicker 
    errorText={this.state.dob ? {} : this.state.dobError} 
    errorStyle={this.state.dob ? {} : errorStyle} 
 >

Upvotes: 2

Related Questions