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

[RFR] Refactor validators to not return translated errors #3339

Merged
merged 42 commits into from
Jun 25, 2019
Merged
Show file tree
Hide file tree
Changes from 39 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
22e82f1
Refactor validators to not return translated errors
djhi Jun 15, 2019
5367385
Added a unstyled ValidationError displaying translated errors
djhi Jun 15, 2019
f6662b8
Fix validate in simple example
djhi Jun 15, 2019
bc6bb9c
Migrate TextInput
djhi Jun 15, 2019
1153e5b
Migrate LongTextInput
djhi Jun 15, 2019
21335c4
Migrate NumberInput
djhi Jun 15, 2019
b84039d
Migrate SelectInput
djhi Jun 15, 2019
d02160d
Fix ValidationError and rename types to avoid confusion
djhi Jun 19, 2019
acaa303
Introduce InputHelperText
djhi Jun 19, 2019
ed94b5b
Use InputHelperText in TextInput
djhi Jun 19, 2019
5370732
Refactor LongTextInput to use TextInput with different default props …
djhi Jun 19, 2019
e83df9c
Migrate SelectInput
djhi Jun 19, 2019
b60dd99
Migrate NumberInput
djhi Jun 19, 2019
89b0d26
Migrate SelectArrayInput
djhi Jun 19, 2019
aa3a745
Migrate RadioButtonGroupInput
djhi Jun 19, 2019
183a080
Migrated AutocompleteArrayInput
djhi Jun 19, 2019
42b94e2
Migrated AutocompleteInput
djhi Jun 19, 2019
52a54d1
Migrate DateInput
djhi Jun 19, 2019
65abc29
Migrated DateTimeInput
djhi Jun 19, 2019
32f98c1
Migrated FIleInput
djhi Jun 19, 2019
9a53443
Migrated NullableBooleanInput
djhi Jun 19, 2019
4a62948
Migrated BooleanInput
djhi Jun 19, 2019
9b02c03
Migrated SelectArrayInput
djhi Jun 19, 2019
d48eedd
Fix after rebase
djhi Jun 19, 2019
055c505
Fix BooleanInput tests
djhi Jun 19, 2019
8dc05ba
Fix ArrayInput tests
djhi Jun 19, 2019
d75deef
Restore unit test with watch mode
djhi Jun 19, 2019
3b7bcc6
Cleanup package.json
djhi Jun 19, 2019
46d5161
Review ValidationError
djhi Jun 19, 2019
15da162
Cleanup imports
djhi Jun 19, 2019
5dfc5d0
Linting
djhi Jun 19, 2019
b0c0e1e
Fix ArrayInput performances
djhi Jun 20, 2019
ee34da5
Review
djhi Jun 20, 2019
8d2ff10
Export InputHelperText
djhi Jun 20, 2019
2115caf
Migrate RichTextInput
djhi Jun 20, 2019
845965c
Fix SelectInput
djhi Jun 20, 2019
3fcf58e
Better ValidationError tests
djhi Jun 20, 2019
b0a37f2
Revert breaking change on BooleanInput
djhi Jun 20, 2019
5cff58f
Add documentation and upgrade
fzaninotto Jun 25, 2019
a1939d8
Remove translation of error arguments
fzaninotto Jun 25, 2019
f76fc1a
Add base test case for InputHelperText
fzaninotto Jun 25, 2019
f8ba430
Add deprecation annotation
fzaninotto Jun 25, 2019
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
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ test-unit: ## launch unit tests

test-unit-watch: ## launch unit tests and watch for changes
echo "Running unit tests..."; \
yarn -s test-unit; \
yarn -s test-unit --watch; \

test-e2e: ## launch end-to-end tests
@if [ "$(build)" != "false" ]; then \
Expand Down
55 changes: 54 additions & 1 deletion UPGRADE.md
Original file line number Diff line number Diff line change
Expand Up @@ -219,4 +219,57 @@ const App = () => (
// ...
</Admin>
);
```
```

## Validators Should Return Non-Translated Messages

Form validators used to return translated error messages - that's why they received the field `props` as argument, including the `translate` function. They don't receive these props anymore, and they must return unstranslated messages instead - react-admin translates validation messages afterwards.

```diff
// in validators/required.js
-const required = () => (value, allValues, props) =>
+const required = () => (value, allValues) =>
value
? undefined
- : props.translate('myroot.validation.required');
+ : 'myroot.validation.required';
```

In case the error message depends on a variable, you can return an object `{ message, args }` instead of a message string:

```diff
-const minLength = (min) => (value, allValues, props) =>
+const minLength = (min) => (value, allValues) =>
value.length >= min
? undefined
- : props.translate('myroot.validation.minLength', { min });
+ : { message: 'myroot.validation.minLength', args: { min } };
```

React-admin core validators have been modified so you don't have to change anything when using them.

```jsx
import {
required,
minLength,
maxLength,
minValue,
number,
email,
} from 'react-admin';

// no change vs 2.x
const validateFirstName = [required(), minLength(2), maxLength(15)];
const validateEmail = email();
const validateAge = [number(), minValue(18)];

export const UserCreate = (props) => (
<Create {...props}>
<SimpleForm>
<TextInput label="First Name" source="firstName" validate={validateFirstName} />
<TextInput label="Email" source="email" validate={validateEmail} />
<TextInput label="Age" source="age" validate={validateAge}/>
</SimpleForm>
</Create>
);
```
39 changes: 36 additions & 3 deletions docs/CreateEdit.md
Original file line number Diff line number Diff line change
Expand Up @@ -565,13 +565,46 @@ React-admin will combine all the input-level functions into a single function lo

Input validation functions receive the current field value, and the values of all fields of the current record. This allows for complex validation scenarios (e.g. validate that two passwords are the same).

**Tip**: Validator functions receive the form `props` as third parameter, including the `translate` function. This lets you build internationalized validators:
**Tip**: If your admin has multi-language support, validator functions should return message *identifiers* rather than messages themselves. React-admin automatically passes these identifiers to the translation function:

```jsx
const required = (message = 'myroot.validation.required') =>
(value, allValues, props) => value ? undefined : props.translate(message);
// in validators/required.js
const required = () => (value, allValues, props) =>
value
? undefined
: 'myroot.validation.required';

// in i18n/en.json
export default {
myroot: {
validation: {
required: 'Required field',
}
}
}
```

If the translation depends on a variable, the validator can return an object rather than a translation identifier:

```jsx
// in validators/minLength.js
const minLength = (min) => (value, allValues, props) =>
value.length >= min
? undefined
: { message: 'myroot.validation.minLength', args: { min } };

// in i18n/en.js
export default {
myroot: {
validation: {
minLength: 'Must be %{min} characters at least',
}
}
}
```

See the [Translation documentation](Translation.md#translating-error-messages) for details.

**Tip**: Make sure to define validation functions or array of functions in a variable, instead of defining them directly in JSX. This can result in a new function or array at every render, and trigger infinite rerender.

{% raw %}
Expand Down
40 changes: 40 additions & 0 deletions docs/Translation.md
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,46 @@ const App = () => (
);
```

## Translating Error Messages

In Create and Edit views, forms can use custom validators. These validator functions should return translation keys rather than translated messages. React-admin automatically passes these identifiers to the translation function:

```jsx
// in validators/required.js
const required = () => (value, allValues, props) =>
value
? undefined
: 'myroot.validation.required';

// in i18n/en.json
export default {
myroot: {
validation: {
required: 'Required field',
}
}
}
```

If the translation depends on a variable, the validator can return an object rather than a translation identifier:

```jsx
// in validators/minLength.js
const minLength = (min) => (value, allValues, props) =>
value.length >= min
? undefined
: { message: 'myroot.validation.minLength', args: { min } };

// in i18n/en.js
export default {
myroot: {
validation: {
minLength: 'Must be %{min} characters at least',
}
}
}
```

## `useTranslate` Hook

If you need to translate messages in your own components, React-admin provides a `useTranslate` hook, which returns the `translate` function:
Expand Down
37 changes: 23 additions & 14 deletions examples/simple/src/comments/PostReferenceInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,28 +49,37 @@ const PostReferenceInput = props => {
);
}, [dispatch, newPostId]);

const handleNewClick = useCallback(event => {
event.preventDefault();
setShowCreateDialog(true);
}, []);
const handleNewClick = useCallback(
event => {
event.preventDefault();
setShowCreateDialog(true);
},
[setShowCreateDialog]
);

const handleShowClick = useCallback(event => {
event.preventDefault();
setShowPreviewDialog(true);
}, []);
const handleShowClick = useCallback(
event => {
event.preventDefault();
setShowPreviewDialog(true);
},
[setShowPreviewDialog]
);

const handleCloseCreate = useCallback(() => {
setShowCreateDialog(false);
}, []);
}, [setShowCreateDialog]);

const handleCloseShow = useCallback(() => {
setShowPreviewDialog(false);
}, []);
}, [setShowPreviewDialog]);

const handleSave = useCallback(post => {
setShowCreateDialog(false);
setNewPostId(post.id);
}, []);
const handleSave = useCallback(
post => {
setShowCreateDialog(false);
setNewPostId(post.id);
},
[setShowCreateDialog, setNewPostId]
);

return (
<Fragment>
Expand Down
4 changes: 2 additions & 2 deletions examples/simple/src/posts/PostCreate.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,12 @@ const PostCreate = ({ permissions, ...props }) => (
const errors = {};
['title', 'teaser'].forEach(field => {
if (!values[field]) {
errors[field] = ['Required field'];
errors[field] = 'Required field';
}
});

if (values.average_note < 0 || values.average_note > 5) {
errors.average_note = ['Should be between 0 and 5'];
errors.average_note = 'Should be between 0 and 5';
}

return errors;
Expand Down
80 changes: 0 additions & 80 deletions packages/ra-core/package-lock.json

This file was deleted.

Loading