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.
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}
>
Related
I have an input with type date inside a form as below:
<Input type="date" defaultValue={this.state.todayDate} onChange={this.handleChangeDate}/> // defaultValue contains today's date
However, when changing the date from the current date (today's date), the state won't be updated and the whole item can't be saved upon submission of the form. This is the handleChangeDate method:
handleChangeDate(event) {
let item = {...this.state.item};
item.timeStamp = event.target.value; // Update time stamp in item
this.setState({item: item}); // Update item in state
}
Any help would be appreciated, thanks alot!
Change defaultValue to value:
<Input type="date" value={this.state.item.timeStamp} onChange={this.handleChangeDate}/> // defaultValue contains today's date
I have question about pnp/sp PeoplePicker.
PeoplePicker has property "required", but wen i use it in my form it is ignored.
This is my PeoplePicker code:
<PeoplePicker
required={true}
context={this.props.spContext}
personSelectionLimit={1}
onChange={this.hcRequestorPP}
showHiddenInUI={false}
principalTypes={[PrincipalType.User]}
ensureUser={true}
resolveDelay={1000}
defaultSelectedUsers={this.props.pRequestor}
disabled={false} />
What am I doing wrong?
Helo,
you are not doing anything wrong :-) Required property based on my knowledge puts asterisk next to people picker label - that's all.
If you want check in the form if user has put something into people picker field, you have to check it by yourself.
My version of form is:
every form value is stored in state.
every form field with its definition (name, type, required, ...) is stored in props (or state, or const, etc.).
before submitting form, I am checking if every required value is filled (code below)
if it is not filled I put error message under the field.
good example to start is here: https://github.com/pnp/sp-dev-fx-webparts/tree/master/samples/react-list-form
checking required
let requiredError: boolean = false;
let fieldErrors: { [fieldName: string]: string } = {...this.state.fieldErrors};
// check required
for (let i: number = 0; i < this.state.fieldsSchema.length; i++) {
if ((this.state.fieldsSchema[i].Required) && (!this.state.data[this.state.fieldsSchema[i].InternalName]) && (this.state.fieldsSchema[i].InternalName !== 'Aktivita')) {
requiredError = true;
fieldErrors = {
...fieldErrors,
[this.state.fieldsSchema[i].InternalName]: strings.FormFields.RequiredValueMessage
};
}
}
if (requiredError === true) {
this.setState({
...this.state,
fieldErrors: fieldErrors,
requiredFieldEmpty: requiredError
});
return;
}
I am trying to use Standard Date picker using below component but however I want to display custom error message when the enterted date is not in the speciied min & max range. But I am not able to achieve it as I could see the standard error message. I implemented the same by referring to : https://developer.salesforce.com/docs/component-library/bundle/lightning:input/example and in this link I can see that the custom error messages can be shown. But nothing worked for me can anyone please help.
https://developer.salesforce.com/docs/component-library/bundle/lightning:input/documentation
<lightning:input aura:id="field
type="date"
name="MyDatefield"
label="MyDateField"
value="2017-09-07"
min="2017-09-05"
messageWhenRangeUnderflow="Select correct date range1"
max="2017-09-22"
messageWhenRangeOverflow="Select correct date range2"
onchange="{!c.checkValidity }"
</aura:component>
This was asked 1 month back but sharing the answer if anybody else runs across this. Use lightning's setCustomValidity() and reportValidity() methods.
Component:
<aura:component >
<lightning:input aura:id="field"
type="date"
name="MyDatefield"
label="MyDateField"
value="2017-09-07"
min="2017-09-05"
max="2017-09-22"
onblur ="{!c.checkValidity }"
/>
</aura:component>
Controller:
({
checkValidity : function(component, event, helper) {
var inputCmp = component.find("field");
inputCmp.setCustomValidity(""); //reset error
var value = inputCmp.get("v.value");
console.log('value: '+value);
var lowerRange = new Date("2017/09/05");
var higherRange = new Date("2017/09/22");
if(!inputCmp.checkValidity()){
if(Date.parse(value)){
if (Date.parse(value) < lowerRange) {
inputCmp.setCustomValidity("Select correct date range1");
}else if (Date.parse(value) > higherRange){
inputCmp.setCustomValidity("Select correct date range2");
}
}else{
inputCmp.setCustomValidity("Invalid value");
}
}
inputCmp.reportValidity();
}
})
I would like to restrict users from selecting particular dates based on business logic in react native ios/ android date pickers. Currently in the document i only see that a min date and max date can be provided.
So is there a way to only restrict lets say (5 , 6, 10, 12 , 18) of a month?
Note: these dates are just an example would change from a case to case scenario
For IOS example
<DatePickerIOS
date={this.state.chosenDate}
onDateChange={(date) => {
if(isAllowedDate(date)) {
this.setState({chosenDate: newDate})
}
else {
this.setState({error:'you can not select this date ...'})
}
}}
/>
use react-native-datepicker module for iOS and Android , set a method to check if date valid or not
render(){
return(
...
<DatePicker
mode="date"
placeholder="select date"
format="YYYY-MM-DD"
onDateChange={this.saveDateIfValid}
/>
...
)
}
saveDateIfValid = (date) =>
{
if(date){
let dateArray = data.split("-");
let validDays = [5,6,10,12,18];
let selectedDay = parseInt(dataArray[2]);
if(validDays.indexOf(selectedDay) > -1){
//date is valid
this.setState({date : date});
return; //end the method
}
}
//not valid
this.setState({date : null});
}
I'using this library for react time picker: https://github.com/YouCanBookMe/react-datetime
But now I have 2 problems.
The time (Am, Pm, HH:mm) in timepicker doesnt'work , because it doesn't change, it remain to 12 : 00 AM
How correctly update state? because if I handle onChange (input manual write), it receive string, that I can't parse and it is invalid date.
My code is:
import DateTime from 'react-datetime';
var moment = require('moment');
handleChangeDate(propertyName, date) {
const event = Object.assign({}, this.state.event);
if (typeof date === 'string') {
date = moment(date);
}
event[propertyName] = data.format('DD/MM/YYYY HH:mm');
this.setState({ event: event });
}
and in Render() I have compoment:
<DateTime dateFormat={"dddd, MMM. Do YYYY, HH:mm (hh:mm a)"} value={this.state.event.to} onChange={this.handleChangeDate.bind(this, 'to')}/>
What is wrong?
check in below link.
Customized calendar will solve your problem.
https://github.com/YouCanBookMe/react-datetime#customize-the-appearance
After choose date in calendar then click on date. It will show the edit option for time.
Example Link
https://codepen.io/simeg/pen/YppLmO
Let it try