Add error validation
This commit is contained in:
1 parent
6ac19000f7
commit
5f96b17595
5 files changed
+178
-70
No files matched your search
@@ -1,5 +1,12 @@
|
||||
import PropTypes from "prop-types";
|
||||
import { Box, ListItem, Autocomplete, TextField } from "@mui/material";
|
||||
import {
|
||||
Box,
|
||||
ListItem,
|
||||
Autocomplete,
|
||||
TextField,
|
||||
Stack,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { useTheme } from "@emotion/react";
|
||||
import SearchIcon from "../../../assets/icons/search.svg?react";
|
||||
|
||||
@@ -49,6 +56,7 @@ const Search = ({
|
||||
sx,
|
||||
multiple = false,
|
||||
isAdorned = true,
|
||||
error,
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
|
||||
@@ -69,24 +77,40 @@ const Search = ({
|
||||
options={options}
|
||||
getOptionLabel={(option) => option[filteredBy]}
|
||||
renderInput={(params) => (
|
||||
<TextField
|
||||
{...params}
|
||||
placeholder="Type to search"
|
||||
InputProps={{
|
||||
...params.InputProps,
|
||||
...(isAdorned && { startAdornment: <SearchAdornment /> }),
|
||||
}}
|
||||
sx={{
|
||||
"& fieldset": {
|
||||
borderColor: theme.palette.border.light,
|
||||
borderRadius: theme.shape.borderRadius,
|
||||
},
|
||||
"& .MuiOutlinedInput-root:hover:not(:has(input:focus)):not(:has(textarea:focus)) fieldset":
|
||||
{
|
||||
<Stack>
|
||||
<TextField
|
||||
{...params}
|
||||
error={Boolean(error)}
|
||||
placeholder="Type to search"
|
||||
InputProps={{
|
||||
...params.InputProps,
|
||||
...(isAdorned && { startAdornment: <SearchAdornment /> }),
|
||||
}}
|
||||
sx={{
|
||||
"& fieldset": {
|
||||
borderColor: theme.palette.border.light,
|
||||
borderRadius: theme.shape.borderRadius,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
"& .MuiOutlinedInput-root:hover:not(:has(input:focus)):not(:has(textarea:focus)) fieldset":
|
||||
{
|
||||
borderColor: theme.palette.border.light,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
{error && (
|
||||
<Typography
|
||||
component="span"
|
||||
className="input-error"
|
||||
color={theme.palette.error.text}
|
||||
mt={theme.spacing(2)}
|
||||
sx={{
|
||||
opacity: 0.8,
|
||||
}}
|
||||
>
|
||||
{error}
|
||||
</Typography>
|
||||
)}
|
||||
</Stack>
|
||||
)}
|
||||
filterOptions={(options, { inputValue }) => {
|
||||
const filtered = options.filter((option) =>
|
||||
@@ -159,6 +183,7 @@ Search.propTypes = {
|
||||
handleChange: PropTypes.func,
|
||||
isAdorned: PropTypes.bool,
|
||||
sx: PropTypes.object,
|
||||
error: PropTypes.string,
|
||||
};
|
||||
|
||||
export default Search;
|
||||
@@ -7,9 +7,8 @@ import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
|
||||
import { LocalizationProvider } from "@mui/x-date-pickers";
|
||||
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
|
||||
import { MobileTimePicker } from "@mui/x-date-pickers/MobileTimePicker";
|
||||
|
||||
import { maintenanceWindowValidation } from "../../../Validation/validation";
|
||||
import dayjs from "dayjs";
|
||||
|
||||
import Select from "../../../Components/Inputs/Select";
|
||||
import Field from "../../../Components/Inputs/Field";
|
||||
import Breadcrumbs from "../../../Components/Breadcrumbs";
|
||||
@@ -17,10 +16,27 @@ import CalendarIcon from "../../../assets/icons/calendar.svg?react";
|
||||
import "./index.css";
|
||||
import Search from "../../../Components/Inputs/Search";
|
||||
import { networkService } from "../../../main";
|
||||
import {
|
||||
MS_PER_SECOND,
|
||||
MS_PER_MINUTE,
|
||||
MS_PER_HOUR,
|
||||
MS_PER_DAY,
|
||||
} from "../../../Utils/timeUtils";
|
||||
|
||||
const MS_LOOKUP = {
|
||||
seconds: MS_PER_SECOND,
|
||||
minutes: MS_PER_MINUTE,
|
||||
hours: MS_PER_HOUR,
|
||||
days: MS_PER_DAY,
|
||||
};
|
||||
|
||||
const repeatConfig = [
|
||||
{ _id: 0, name: "Don't repeat", value: "none" },
|
||||
{ _id: 1, name: "Repeat daily", value: "daily" },
|
||||
{
|
||||
_id: 1,
|
||||
name: "Repeat daily",
|
||||
value: "daily",
|
||||
},
|
||||
{ _id: 2, name: "Repeat weekly", value: "weekly" },
|
||||
];
|
||||
|
||||
@@ -28,7 +44,10 @@ const durationConfig = [
|
||||
{ _id: 0, name: "seconds" },
|
||||
{ _id: 1, name: "minutes" },
|
||||
{ _id: 2, name: "hours" },
|
||||
{ _id: 3, name: "days" },
|
||||
{
|
||||
_id: 3,
|
||||
name: "days",
|
||||
},
|
||||
];
|
||||
|
||||
const getValueById = (config, id) => {
|
||||
@@ -38,8 +57,11 @@ const getValueById = (config, id) => {
|
||||
|
||||
const getIdByValue = (config, name) => {
|
||||
const item = config.find((config) => {
|
||||
if (config.value) return config.value === name;
|
||||
else return config.name === name;
|
||||
if (config.value) {
|
||||
return config.value === name;
|
||||
} else {
|
||||
return config.name === name;
|
||||
}
|
||||
});
|
||||
return item ? item._id : null;
|
||||
};
|
||||
@@ -51,13 +73,14 @@ const CreateMaintenance = () => {
|
||||
const [search, setSearch] = useState("");
|
||||
const [form, setForm] = useState({
|
||||
repeat: "none",
|
||||
startDate: dayjs().toISOString(),
|
||||
startTime: dayjs().toISOString(),
|
||||
startDate: dayjs(),
|
||||
startTime: dayjs(),
|
||||
duration: "",
|
||||
durationUnit: "seconds",
|
||||
name: "",
|
||||
monitors: [],
|
||||
});
|
||||
const [errors, setErrors] = useState({});
|
||||
|
||||
useEffect(() => {
|
||||
const fetchMonitors = async () => {
|
||||
@@ -72,20 +95,82 @@ const CreateMaintenance = () => {
|
||||
fetchMonitors();
|
||||
}, [authToken, user]);
|
||||
|
||||
const buildErrors = (prev, id, error) => {
|
||||
const updatedErrors = { ...prev };
|
||||
if (error) {
|
||||
updatedErrors[id] = error.details[0].message;
|
||||
} else {
|
||||
delete updatedErrors[id];
|
||||
}
|
||||
return updatedErrors;
|
||||
};
|
||||
|
||||
const handleSearch = (value) => {
|
||||
setSearch(value);
|
||||
};
|
||||
|
||||
const handleSelectMonitors = (monitors) => {
|
||||
setForm({ ...form, monitors });
|
||||
const { error } = maintenanceWindowValidation.validate(
|
||||
{ monitors },
|
||||
{ abortEarly: false }
|
||||
);
|
||||
setErrors((prev) => {
|
||||
return buildErrors(prev, "monitors", error);
|
||||
});
|
||||
};
|
||||
|
||||
const handleFormChange = (key, value) => {
|
||||
setForm({ ...form, [key]: value });
|
||||
const { error } = maintenanceWindowValidation.validate(
|
||||
{ [key]: value },
|
||||
{ abortEarly: false }
|
||||
);
|
||||
setErrors((prev) => {
|
||||
return buildErrors(prev, key, error);
|
||||
});
|
||||
};
|
||||
|
||||
const handleTimeChange = (key, newTime) => {
|
||||
setForm({ ...form, [key]: newTime });
|
||||
const { error } = maintenanceWindowValidation.validate(
|
||||
{ [key]: newTime },
|
||||
{ abortEarly: false }
|
||||
);
|
||||
setErrors((prev) => {
|
||||
return buildErrors(prev, key, error);
|
||||
});
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
const { error } = maintenanceWindowValidation.validate(form, {
|
||||
abortEarly: false,
|
||||
});
|
||||
|
||||
// If errors, return early
|
||||
if (error) {
|
||||
const newErrors = {};
|
||||
error.details.forEach((err) => {
|
||||
newErrors[err.path[0]] = err.message;
|
||||
});
|
||||
setErrors(newErrors);
|
||||
console.log(error);
|
||||
return;
|
||||
}
|
||||
// Build timestamp for maintenance window from startDate and startTime
|
||||
const startTimestamp = dayjs(form.startDate);
|
||||
startTimestamp
|
||||
.set("hour", form.startTime.hour())
|
||||
.set("minute", form.startTime.minute())
|
||||
.set("second", form.startTime.second())
|
||||
.set("millisecond", form.startTime.millisecond());
|
||||
|
||||
// Build end timestamp for maintenance window
|
||||
const MS_MULTIPLIER = MS_LOOKUP[form.durationUnit];
|
||||
const durationInMs = form.duration * MS_MULTIPLIER;
|
||||
const endTimeStamp = startTimestamp.add(durationInMs);
|
||||
console.log(startTimestamp.toISOString());
|
||||
console.log(endTimeStamp.toISOString());
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -134,7 +219,7 @@ const CreateMaintenance = () => {
|
||||
borderLeftColor={theme.palette.border.light}
|
||||
>
|
||||
<Select
|
||||
id="maintenance-repeat"
|
||||
id="repeat"
|
||||
name="maintenance-repeat"
|
||||
label="Maintenance Repeat"
|
||||
value={getIdByValue(repeatConfig, form.repeat)}
|
||||
@@ -150,8 +235,10 @@ const CreateMaintenance = () => {
|
||||
<Typography component="h3">Date</Typography>
|
||||
<LocalizationProvider dateAdapter={AdapterDayjs}>
|
||||
<DatePicker
|
||||
id="startDate"
|
||||
disablePast
|
||||
disableHighlightToday
|
||||
value={form.startDate}
|
||||
slots={{ openPickerIcon: CalendarIcon }}
|
||||
slotProps={{
|
||||
switchViewButton: { sx: { display: "none" } },
|
||||
@@ -192,8 +279,9 @@ const CreateMaintenance = () => {
|
||||
}}
|
||||
sx={{}}
|
||||
onChange={(newDate) => {
|
||||
handleTimeChange("startDate", newDate.toISOString());
|
||||
handleTimeChange("startDate", newDate);
|
||||
}}
|
||||
error={errors["startDate"]}
|
||||
/>
|
||||
</LocalizationProvider>
|
||||
</Stack>
|
||||
@@ -212,10 +300,10 @@ const CreateMaintenance = () => {
|
||||
<Stack direction="row">
|
||||
<LocalizationProvider dateAdapter={AdapterDayjs}>
|
||||
<MobileTimePicker
|
||||
id="maintenance-start-time"
|
||||
value={dayjs(form.startTime)}
|
||||
id="startTime"
|
||||
value={form.startTime}
|
||||
onChange={(newTime) => {
|
||||
handleTimeChange("startTime", newTime.toISOString());
|
||||
handleTimeChange("startTime", newTime);
|
||||
}}
|
||||
slotProps={{
|
||||
nextIconButton: { sx: { ml: theme.spacing(2) } },
|
||||
@@ -241,6 +329,7 @@ const CreateMaintenance = () => {
|
||||
},
|
||||
},
|
||||
}}
|
||||
error={errors["startTime"]}
|
||||
/>
|
||||
</LocalizationProvider>
|
||||
</Stack>
|
||||
@@ -254,14 +343,15 @@ const CreateMaintenance = () => {
|
||||
<Stack direction="row" spacing={theme.spacing(8)}>
|
||||
<Field
|
||||
type="number"
|
||||
id="maintenance-duration"
|
||||
id="duration"
|
||||
value={form.duration}
|
||||
onChange={(event) => {
|
||||
handleFormChange("duration", event.target.value);
|
||||
}}
|
||||
error={errors["duration"]}
|
||||
/>
|
||||
<Select
|
||||
id="maintenance-unit"
|
||||
id="durationUnit"
|
||||
value={getIdByValue(durationConfig, form.durationUnit)}
|
||||
items={durationConfig}
|
||||
onChange={(event) => {
|
||||
@@ -270,6 +360,7 @@ const CreateMaintenance = () => {
|
||||
getValueById(durationConfig, event.target.value)
|
||||
);
|
||||
}}
|
||||
error={errors["durationUnit"]}
|
||||
/>
|
||||
</Stack>
|
||||
</Stack>
|
||||
@@ -292,12 +383,13 @@ const CreateMaintenance = () => {
|
||||
</Box>
|
||||
<Box>
|
||||
<Field
|
||||
id="maintenance-name"
|
||||
id="name"
|
||||
placeholder="Maintenance at __ : __ for ___ minutes"
|
||||
value={form.name}
|
||||
onChange={(event) => {
|
||||
handleFormChange("name", event.target.value);
|
||||
}}
|
||||
error={errors["name"]}
|
||||
/>
|
||||
</Box>
|
||||
</Stack>
|
||||
@@ -309,6 +401,7 @@ const CreateMaintenance = () => {
|
||||
</Box>
|
||||
<Box>
|
||||
<Search
|
||||
id={"monitors"}
|
||||
multiple={true}
|
||||
isAdorned={false}
|
||||
options={monitors ? monitors : []}
|
||||
@@ -317,6 +410,7 @@ const CreateMaintenance = () => {
|
||||
value={search}
|
||||
handleInputChange={handleSearch}
|
||||
handleChange={handleSelectMonitors}
|
||||
error={errors["monitors"]}
|
||||
/>
|
||||
</Box>
|
||||
</Stack>
|
||||
@@ -334,7 +428,7 @@ const CreateMaintenance = () => {
|
||||
<Button
|
||||
variant="contained"
|
||||
color="primary"
|
||||
onClick={() => console.log(form)}
|
||||
onClick={handleSubmit}
|
||||
disabled={false}
|
||||
>
|
||||
Create maintenance
|
||||
|
||||
@@ -112,7 +112,7 @@ const CreateMonitor = () => {
|
||||
{ [name]: value },
|
||||
{ abortEarly: false }
|
||||
);
|
||||
|
||||
console.log(error);
|
||||
setErrors((prev) => {
|
||||
const updatedErrors = { ...prev };
|
||||
if (error) updatedErrors[name] = error.details[0].message;
|
||||
|
||||
@@ -4,6 +4,11 @@ import timezone from "dayjs/plugin/timezone";
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
|
||||
export const MS_PER_SECOND = 1000;
|
||||
export const MS_PER_MINUTE = 60 * MS_PER_SECOND;
|
||||
export const MS_PER_HOUR = 60 * MS_PER_MINUTE;
|
||||
export const MS_PER_DAY = 24 * MS_PER_HOUR;
|
||||
|
||||
export const formatDuration = (ms) => {
|
||||
const seconds = Math.floor(ms / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import joi from "joi";
|
||||
import dayjs from "dayjs";
|
||||
|
||||
const nameSchema = joi
|
||||
.string()
|
||||
@@ -113,50 +114,33 @@ const imageValidation = joi.object({
|
||||
}),
|
||||
});
|
||||
|
||||
const maintenanceWindowValidation = joi.object({
|
||||
repeat: joi.number().valid(1, 2, 3).required().messages({
|
||||
"number.base": "Repeat must be a number.",
|
||||
"any.only": "Repeat must be one of [1, 2, 3].",
|
||||
"any.required": "Repeat is required.",
|
||||
}),
|
||||
date: joi.date().required().messages({
|
||||
"date.base": "Date must be a valid date.",
|
||||
"any.required": "Date is required.",
|
||||
}),
|
||||
startTime: joi.string().required().messages({
|
||||
"string.base": "Start time must be a valid time.",
|
||||
"any.required": "Start time is required.",
|
||||
}),
|
||||
duration: joi.number().required().messages({
|
||||
"number.empty": "duration is required.",
|
||||
"number.base": "Duration must be a number.",
|
||||
"any.required": "Duration is required.",
|
||||
}),
|
||||
unit: joi.string().valid("minutes", "hours", "days").required().messages({
|
||||
"string.base": "Unit must be a string.",
|
||||
"any.only": "Unit must be one of ['minutes', 'hours', 'days'].",
|
||||
"any.required": "Unit is required.",
|
||||
}),
|
||||
displayName: joi.string().max(50).required().messages({
|
||||
"string.empty": "Display name is required.",
|
||||
"string.max": "Display name must be less than 50 characters long",
|
||||
}),
|
||||
addMonitors: joi.string().max(50).required().messages({
|
||||
"string.empty": "Add monitors is required.",
|
||||
"string.max": "Add monitors must be less than 50 characters long",
|
||||
}),
|
||||
});
|
||||
|
||||
const settingsValidation = joi.object({
|
||||
ttl: joi.number().required().messages({
|
||||
"string.empty": "TTL is required",
|
||||
}),
|
||||
});
|
||||
|
||||
const dayjsValidator = (value, helpers) => {
|
||||
if (!dayjs(value).isValid()) {
|
||||
return helpers.error("any.invalid");
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
const maintenanceWindowValidation = joi.object({
|
||||
repeat: joi.string(),
|
||||
startDate: joi.custom(dayjsValidator, "Day.js date validation"),
|
||||
startTime: joi.custom(dayjsValidator, "Day.js date validation"),
|
||||
duration: joi.number(),
|
||||
durationUnit: joi.string(),
|
||||
name: joi.string(),
|
||||
monitors: joi.array().min(1),
|
||||
});
|
||||
|
||||
export {
|
||||
credentials,
|
||||
imageValidation,
|
||||
monitorValidation,
|
||||
maintenanceWindowValidation,
|
||||
settingsValidation,
|
||||
maintenanceWindowValidation,
|
||||
};
|
||||
Reference in new issue
Block a user