I want to create a custom validation starting from the validation below. But I'm not successful so far. I had visited this site and followed the codes in his "Custom validation rules" but I can't replicate it.
The isBefore
method is working fine, but the validation does not. And also how can we put a custom message with this custom validation?
const isBefore = (date1, date2) => moment(date1).isBefore(moment(date2));
const rules = {
publishedDate: {
required: 'The published date is required.',
before: isBefore(scheduledDate, expiredDate)
},
}
<Controller
control={control}
name="publishedDate"
rules={rules.publishedDate}
render={({ onChange }) => (
<DatePicker
className="mb-px-8"
onChange={(value) => {
setPublishedDate(value);
onChange(value);
}}
minDate={new Date()}
value={publishedDate}
/>
)}
/>
Try using rules of react-hook-form to add validations
<Controller
name="currentName"
control={control}
render={({ field }) => (
<TextField
value={field.value}
onChange={field.onChange}
inputRef={field.ref}
variant="outlined"
size="small"
fullWidth
autoComplete="off"
helperText={helperText}
/>
)}
rules={{
validate: {
required: (value) => {
if (value === "SomeValue") return 'Some Message';
if (!value) return '*Required';
}
},
maxLength: 5
}}
defaultValue=""
/>