1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-07 00:58:02 +00:00

Add Custom Type Checking Error Messages With Yup as a javascript til

This commit is contained in:
jbranchaud
2018-03-08 09:50:43 -06:00
parent ba4b629c53
commit 17a3a558e5
2 changed files with 27 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
For a steady stream of TILs from a variety of rocketeers, checkout
[til.hashrocket.com](https://til.hashrocket.com/).
_635 TILs and counting..._
_636 TILs and counting..._
---
@@ -227,6 +227,7 @@ _635 TILs and counting..._
- [Computed Property Names In ES6](javascript/computed-property-names-in-es6.md)
- [Create An Array Containing 1 To N](javascript/create-an-array-containing-1-to-n.md)
- [Create Bootstrapped Apps With Yarn](javascript/create-bootstrapped-apps-with-yarn.md)
- [Custom Type Checking Error Messages With Yup](javascript/custom-type-checking-error-messages-with-yup.md)
- [Default And Named Exports From The Same Module](javascript/default-and-named-exports-from-the-same-module.md)
- [Destructuring The Rest Of An Array](javascript/destructuring-the-rest-of-an-array.md)
- [Enable ES7 Transforms With react-rails](javascript/enable-es7-transforms-with-react-rails.md)

View File

@@ -0,0 +1,25 @@
# Custom Type Checking Error Messages With Yup
In [Yup Schemas Are Validated
Asynchronously](https://github.com/jbranchaud/til/blob/master/javascript/yup-schemas-are-validated-asynchronously.md),
I showed how to create a simple schema that allows you to enforce that a
value is a number.
```javascript
const numSchema = yup.number();
```
If we use this schema to validate something that isn't a number, Yup will
provide a lengthy default message. Here is what we get if I validate against
`'hey'`:
> this must be a `number` type, but the final value was: `NaN` (cast from
> the value `"hey"`).
This value isn't necessarily suitable for displaying to a user. We can
customize the type checking error message by redefining our schema with the
`typeError()` function:
```javascript
const numSchema = yup.number().typeError("Invalid number");
```