Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve validation on JSONField fields #6607

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/volto/news/6576.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improve the usability of the ObjectBrowser when inputting a manual value, checking it on blur, and adding a local validator. @sneridagh
36 changes: 28 additions & 8 deletions packages/volto/src/components/manage/Form/Form.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -585,14 +585,34 @@ class Form extends Component {
title={this.props.intl.formatMessage(messages.error)}
content={
<ul>
{Object.keys(errors).map((err, index) => (
<li key={index}>
<strong>
{this.props.schema.properties[err].title || err}:
</strong>{' '}
{errors[err]}
</li>
))}
{Object.keys(errors).map((err, index) => {
return (
<React.Fragment key={index}>
{typeof errors[err] === 'object' &&
!Array.isArray(errors[err]) ? (
Object.keys(errors[err]).map((nestedErr, index) => {
return (
<li key={index}>
<strong>
{this.props.schema.properties[err].title ||
errors[err][nestedErr]}
:
</strong>{' '}
{`[${nestedErr}]: ${errors[err][nestedErr]}`}
</li>
);
})
) : (
<li key={index}>
<strong>
{this.props.schema.properties[err].title || err}:
</strong>{' '}
{errors[err]}
</li>
)}
</React.Fragment>
);
})}
</ul>
}
/>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ import { Image, Label, Popup, Button } from 'semantic-ui-react';
import {
flattenToAppURL,
isInternalURL,
isUrl,
normalizeUrl,
removeProtocol,
} from '@plone/volto/helpers/Url/Url';
import { urlValidator } from '@plone/volto/helpers/FormValidation/validators';
import { searchContent } from '@plone/volto/actions/search/search';
import withObjectBrowser from '@plone/volto/components/manage/Sidebar/ObjectBrowser';
import { defineMessages, injectIntl } from 'react-intl';
Expand Down Expand Up @@ -102,6 +102,7 @@ export class ObjectBrowserWidgetComponent extends Component {
state = {
manualLinkInput: '',
validURL: false,
errors: [],
};

constructor(props) {
Expand Down Expand Up @@ -230,7 +231,16 @@ export class ObjectBrowserWidgetComponent extends Component {

validateManualLink = (url) => {
if (this.props.allowExternals) {
return isUrl(url);
const error = urlValidator({
value: url,
formatMessage: this.props.intl.formatMessage,
});
if (error && url !== '') {
this.setState({ errors: [error] });
} else {
this.setState({ errors: [] });
}
return !Boolean(error);
} else {
return isInternalURL(url);
}
Expand Down Expand Up @@ -341,9 +351,14 @@ export class ObjectBrowserWidgetComponent extends Component {
onChange(id, this.props.return === 'single' ? null : []);
};

const props = {
...this.props,
error: this.props.error.concat(this.state.errors),
};

return (
<FormFieldWrapper
{...this.props}
{...props}
className={description ? 'help text' : 'text'}
>
<div
Expand Down Expand Up @@ -372,6 +387,7 @@ export class ObjectBrowserWidgetComponent extends Component {
items.length === 0 &&
this.props.mode !== 'multiple' && (
<input
onBlur={this.onSubmitManualLink}
onKeyDown={this.onKeyDownManualLink}
onChange={this.onManualLinkInput}
value={this.state.manualLinkInput}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ const ObjectListWidget = (props) => {
value = [],
onChange,
schemaExtender,
error = {},
} = props;
const [localActiveObject, setLocalActiveObject] = React.useState(
props.activeObject ?? value.length - 1,
Expand Down Expand Up @@ -243,6 +244,7 @@ const ObjectListWidget = (props) => {
);
onChange(id, newvalue);
}}
errors={error}
/>
</Segment>
</Accordion.Content>
Expand Down
29 changes: 29 additions & 0 deletions packages/volto/src/helpers/FormValidation/FormValidation.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,31 @@ const validateFieldsPerFieldset = (
);
}

// Validation per JSONField type with own schema
let jsonFieldErrors = [];
if (
field.factory === 'JSONField' &&
field.widgetOptions?.frontendOptions?.schema
) {
const JSONFieldSchema = config.getUtility({
name: fieldId,
type: 'schema',
dependencies: { fieldName: fieldId },
});

jsonFieldErrors = validateFieldsPerFieldset(
JSONFieldSchema.method({
intl: {
formatMessage: () => {},
},
formData: {},
}),
fieldData || {},
formatMessage,
touchedField,
);
}

const mergedErrors = [
...specificFieldErrors,
...fieldErrors,
Expand All @@ -232,6 +257,10 @@ const validateFieldsPerFieldset = (
...blockTypeFieldErrors,
];
}

if (!isEmpty(jsonFieldErrors)) {
errors[fieldId] = { ...jsonFieldErrors };
}
});

return errors;
Expand Down
50 changes: 50 additions & 0 deletions packages/volto/src/helpers/FormValidation/FormValidation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -988,5 +988,55 @@ describe('FormValidation', () => {
customField: [messages.isValidURL.defaultMessage],
});
});

it('JSONField - Basic Required', () => {
let JSONSchemaField = ({ intl }) => ({
properties: {
innerJSONField: {
title: 'Default field',
description: '',
},
},
required: ['innerJSONField'],
});
config.registerUtility({
type: 'schema',
dependencies: { fieldName: 'customJSONSchemaField' },
method: JSONSchemaField,
});
let newSchema = {
properties: {
...schema.properties,
customField: {
title: 'Default field',
description: '',
},
customJSONSchemaField: {
factory: 'JSONField',
title: 'JSON Field',
widgetOptions: {
frontendOptions: {
schema: 'customJSONSchemaField',
},
},
},
},
required: [],
};

expect(
FormValidation.validateFieldsPerFieldset({
schema: newSchema,
formData: {
otherField: 'test',
},
formatMessage,
}),
).toEqual({
customJSONSchemaField: {
innerJSONField: [messages.required.defaultMessage],
},
});
});
});
});
Loading