Skip to content

Commit

Permalink
Validate against schema in bluk update model
Browse files Browse the repository at this point in the history
  • Loading branch information
Krupa Rami committed Oct 21, 2024
1 parent 6866b11 commit db55667
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions packages/app/components/json-patch-operation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,32 @@ const JSONPatchOperation = (props: Props) => {
const [path, setPath] = useState('')
const [pathValue, setPathValue] = useState('')
const [formData, setFormData] = useState({})
const [validationErrors, setValidationErrors] = useState([])

const schema = JSON.parse(model.schema)
// Initial schema template
const [initialSchema, setInitialSchema] = useState({})

// Validation function
const validateAgainstSchema = (data: any, schema: any) => {
const errors: string[] = [];

for (const key in schema.properties) {
const propertySchema = schema.properties[key];
const value = data[key];

if (propertySchema.required && value === undefined) {
errors.push(`${key} is required`);
}

if (propertySchema.type && typeof value !== propertySchema.type) {
errors.push(`${key} should be of type ${propertySchema.type}`);
}
}

return errors;
};

useEffect(() => {
updateOperations({
...field,
Expand Down Expand Up @@ -87,6 +108,8 @@ const JSONPatchOperation = (props: Props) => {
const handleFormDataChange = (data: any) => {
if (data && data.formData.pathValue !== pathValue) {
setPathValue(data.formData.pathValue);
const errors = validateAgainstSchema(data.formData, initialSchema);
setValidationErrors(errors);
}
};

Expand Down Expand Up @@ -145,6 +168,13 @@ const JSONPatchOperation = (props: Props) => {
</Button>
</Col>
</Row>
{validationErrors.length > 0 && (
<div className="alert alert-danger">
{validationErrors.map((error) => (
[error]
))}
</div>
)}
{path && (
<Row>
<Col>
Expand Down

0 comments on commit db55667

Please sign in to comment.