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

Add setLocale example with functions #645

Merged
merged 1 commit into from
Oct 16, 2019
Merged
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
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,35 @@ schema.validate({ name: 'jimmy', age: 11 }).catch(function(err) {
});
```

If you need multi-language support, Yup has got you covered. The function `useLocale` accepts functions that can be used to generate error objects with translation keys and values. Just get this output and feed it into your favorite i18n library.

```js
import { setLocale } from 'yup';

setLocale({
// use constant translation keys for messages without values
mixed: {
default: 'field_invalid',
},
// use functions to generate an error object that includes the value from the schema
number: {
min: ({ min }) => ({ key: 'field_too_short', values: { min } }),
max: ({ max }) => ({ key: 'field_too_big', values: { max } }),
},
});

// now use Yup schemas AFTER you defined your custom dictionary
let schema = yup.object().shape({
name: yup.string(),
age: yup.number().min(18),
});

schema.validate({ name: 'jimmy', age: 11 }).catch(function(err) {
err.name; // => 'ValidationError'
err.errors; // => [{ key: 'field_too_short', values: { min: 18 } }]
});
```

## API

### `yup`
Expand Down