From ba4b629c53973c3d8ffc40971942b6840fe5515a Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Wed, 7 Mar 2018 12:53:11 -0600 Subject: [PATCH] Add Yup Schemas Are Validated Asynchronously as a javascript til --- README.md | 3 +- ...up-schemas-are-validated-asynchronously.md | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 javascript/yup-schemas-are-validated-asynchronously.md diff --git a/README.md b/README.md index 42d1b8f..4a418cc 100644 --- a/README.md +++ b/README.md @@ -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/). -_634 TILs and counting..._ +_635 TILs and counting..._ --- @@ -256,6 +256,7 @@ _634 TILs and counting..._ - [Waiting On Multiple Promises](javascript/waiting-on-multiple-promises.md) - [Who Am I: NPM Edition](javascript/who-am-i-npm-edition.md) - [Yarn Commands Without The Emojis](javascript/yarn-commands-without-the-emojis.md) +- [Yup Schemas Are Validated Asynchronously](javascript/yup-schemas-are-validated-asynchronously.md) ### Linux diff --git a/javascript/yup-schemas-are-validated-asynchronously.md b/javascript/yup-schemas-are-validated-asynchronously.md new file mode 100644 index 0000000..28eb0f7 --- /dev/null +++ b/javascript/yup-schemas-are-validated-asynchronously.md @@ -0,0 +1,33 @@ +# Yup Schemas Are Validated Asynchronously + +[Yup](https://github.com/jquense/yup) provides a flexible object schema +validation DSL. For instance, if you want to enforce that a certain value is +a number, you can define something like this: + +```javascript +const numSchema = yup.number(); +``` + +You can then validate anything against that schema. + +```javascript +const validator = (val) => { + numSchema.validate(val) + .then(result => { + console.log(result); // it is the value of `val` + return true; + }) + .catch(error => { + console.log(error.errors); // array of validation error messages + return false; + }); +}; +``` + +The validation is async, so if it succeeds the `then` block is hit. If the +validation fails, it will fall through to the `catch`. + +```javascript +validator(5) // => true +validator('what') // => false +```