Introduction to Validation in React with Yup

The JavaScript Object Schema Validator and Object Parser to use with React

In this article we will visit why you should be using Yup in your React projects, what it does exactly, and how to make the most out of the package to simplify your code, with examples.

Yup is designed for front-end browser based use. If you are interested in server-side object schema validation with NodeJS, take a look at my article on Joi:

Why should you care about Yup?

Yup makes our lives far easier for validating the data our apps consume and manipulate, in an abstract way that does not interfere with the rest of our business logic.

Web apps built on JavaScript Frameworks are now highly interactive and mutable in and of themselves; that is what the end user has come to expect. With this comes a large amount of data exchange, whether it be from API requests, form submissions, or custom objects to handle our state.

We need to make sure we are delivering data that our components expect to work with, otherwise we will be dealing with unintended consequences in the form of failed component renders or app crashes — we don’t want this.

The general gist of Yup

So how does Yup work exactly?

With Yup, we create a Yup formatted object that resembles our intended schema for an object, and then use Yup utility functions to check if our data objects match this schema — hence validating them.

A Schema Object

Let’s use form validation as a use case for our Yup example.

Note: Form validation is by no means the only use case for Yup — use it to validate any object that you need to, whether you are retrieving data from your APIs or an external API library, or simply working with multiple objects or arrays within your project that need to adhere to a particular schema.

With that said, now imagine I am creating a checkout address form — which may resemble the following structure:

{ 
    email_address: email <required>
    full_name: string, <required>
    house_no: int,
    address_1: string <required>,
    address_2: string,
    post_code: string <required>
    timestamp: date <required>
}

This is the type of data I am expecting from this form, or my schema for a particular object. If my object does not match this schema, it is not valid.

Notice that I have treated the email_address field as an email data type. This is not an error. Yup can test whether a value is an email address with one method call . Likewise with our timestamp value — Yup can test whether this value is a date.

What does this look like as a Yup schema object? Something like this:

const checkoutAddressSchema = yup.object().shape({
  email_address: yup
      .string()
      .email()
      .required(),
  full_name: yup
      .string()
      .required(),
  house_no: yup
      .number()
      .required()
      .positive()
      .integer(),
  address_1: yup
      .string()
      .required(),
  address_2: yup
      .string(),
  post_code: yup
      .string()
      .required(),
  timestamp: yup
      .date()
      .default(() => (new Date()),
   }),
});

A Yup schema is an immutable object responsible for validating an object.

This code is self explanatory: We can see for ourselves the responsibility of this object in a detailed way without having to add a single comment.

Each validator has its own method. This granularity allows us as developers to combine as many validators as we see fit for our data validation.

Data types such as stringintegerbooleanarrayobject and date are all callable validators within Yup, making it simple for Yup newcomers to begin using the code.

However, Yup goes way beyond simple data types. In the above example we also use validators like emailrequired, and positive, allowing me to check whether a value is representative of an email address, whether a value exists and whether a number is positive respectively. (we also have notRequired to use for greater readability of your schema).

This is great, abstract, reusable design. We can even assign default values with an embedded function, as the above example demonstrates with the timestamp field:

 ...
   timestamp: yup
      .date()
      .default(() => (new Date()),
   }
...

default() can be anything you wish to assign: it takes any value. The function can be expanded and treated like any other to include any logic you need to process in order to generate a default value:

...
   timestamp: yup
      .date()
      .default(() => {
         //check for stuff           
         return new Date();
      }),
   }
...

Validating Objects with My Schema

Now we have a schema for our checkout address form, we can then use it to validate the data we receive from it. Let’s say I receive the following data:

let addressFormData = {
   email_address: 'ross@jkrbinvestments.com',
   full_name: 'Ross Bulat',
   house_no: null,
   address_1: 'My Street Name',
   post_code: 'AB01 0AB',
}

As you can see, the address_2 and timestamp fields are missing from here — but they are not required in our schema, so the object will still be valid.

From here I would like to demonstrate 3 things:

  • Check if my object is valid. So a true or false result of whether my object is indeed a valid checkout address object.
  • Validate the object. E.g. use my schema to fill in any default values. This also type casts our object.
  • Visit the cast() method of Yup, that type casts an object without validating it.

Checking if the object is valid

To do this, we use yup.isValid(), which will look like the following when applied to our example:

const valid = await checkoutAddressSchema.isValid(addressFormData);

isValid() returns a promise, so we can either treat this with async and await as demonstrated above, or use callback syntax:

checkoutAddressSchema
  .isValid(addressFormData)
  .then(function(valid) {
      
     //valid - true or false
  });

I prefer using await for cleaner syntax.

Validating the Object

In most cases we will require actually validating the object: process it to adhere to your schema expectations. In our example, we are expecting a timestamp value, and we have a default value if it is missing.

Let’s validate our address form with the following:

await checkoutAddressSchema.validate(addressFormData);

Now our object will be suitable for further processing.

Casting an Object

With the above example, validate(), we are checking whether our data is valid, and we are running validation on it. This is a handy shortcut that you may find you use the majority of time. However, we could just run an object through a cast() method that checks and fixes its types.

With our checkout address form, we may have a string that represents our house_no, whereas my schema expects an integer. cast() will fix this. It would also convert a timestamp string into our Date object if we indeed provided a timestamp string.

Cast is called like so:

checkoutAddressSchema.cast(addressFormData);

Indispensable Tool?

At this point it is becoming clear that Yup adds an extra vital layer of data security to our apps in a concise way. Validation becomes much less of a headache, and actually a joy to write and read because of the simplicity of the syntax and abstraction of the Yup library.

To expand your initial understanding of Yup, let’s visit some other useful methods available within the package.

Miscellaneous Useful Methods

  • Remember our form data structure outlined at the top of the article? This can be retrieved from a Yup object with the describe() methoddescribe() collects the object schema details and serializes them into a separate object.
  • Want to combine 2 schemas into one? Use the concat() method. Perhaps you are combining multiple objects into one API call body, and therefore want to validate the entire body with one Yup object. concat() will come in handy for this.
  • Aborting validation early. By default Yup runs through an entire validation process and collects errors as it runs, and returns them all once validation is complete. We may not want to do this. We can use abortEarly to stop validation execution as soon as the first error crops up. abortEarly is passed as an options argument within validate():
await checkoutAddressSchema.validate(addressFormData, { abortEarly: false })
  • Yup has some great string utilities, such as trim(), that removes whitespace around a string. uppercase() and lowercase() are available to enforce capitalising or not.
  • Yup also has some great number utilities, such as min() and max(), as well as round()morethan()lessthan(), and truncate().
  • Yup supports regex, allowing you to utilise regular expressions.

Installing Yup in React Projects

Let’s move on how to install Yup in your projects, and visit some resources available for further reading.

Visit the NPMJS page or Github project for their official documentation.

Install yup with npm using the following command:

npm i yup

Importing Yup

Yup has the flexibility to be imported as an entire library, or as separate components that only your component needs.

Import the entire library with:

import * as yup from 'yup';

I recommend importing the entire library as you start developing, saving you the hassle of revisiting your imports every time you introduce a new Yup object as your forms evolve. When your app is ready to be built, revisit Yup to check whether you are only using a limited amount of components — perhaps you are only utilising the required and string objects — in this case we can simply import those 2 things:

import { string, required } from 'yup';

Overall though, if you are utilizing more than around 5 components, it can become a code smell to be importing this many objects.

Where to go from here

Now you should have a solid understanding of what Yup is, why it is used, and perhaps some ideas on how it can be implemented in your projects!

Take some time to explore the documentation, which lists all the validators available. Only after exploring everything the package has to offer will you have a well-rounded understanding of how it can fully benefit your apps.

However, Yup can easily be built upon by simply refactoring your validators, so there is no harm in jumping straight into some implementation to increase familiarity of the workflow, before jumping into more documentation detail.

Yup may continue to play a greater role within your app as development progresses, therefore you may also find yourself refactoring some data structures to further take advantage of the Yup workflow in the form of abstracting your data into smaller, more reusable formats.

Ross Bulat

Most popular Medium publications welcoming submissions

Here’s a good Medium leaderboard if you’re looking for an easy way to find even more publications.

Most popular websites looking for content

Here are places where you can promote your content. These can be considered as low hanging fruit and are a great place to start in your outreach efforts.

Fame or Riches?

The the question that one who has the intention to start a business has to ask before commencing with the registration of it or working around the idea/ product is, do I wanna be famous or be rich? This is how Abednigo Tau of Tuta-Me see it:

Recently I came across a South African Entrepreneur who was being interviewed about some of the challenges and failures he had experienced in his clothing retail business, the business is mainly from what I can gather a consumer facing business. Right after watching the interview I went onto social media to see his Instagram account, and there it was , his title , •Celebrity Entrepreneur• , this lead me to ask an introspective question to myself , do you want to be famous or do you want to be rich? In my mind celebrity entrepreneur is a paradox , and oxymoron , two contradictory words that should not follow each other. Look-at my English , Mrs Meyer, my English teacher would be proud .

You see as a big movie star, musician , rockstar, you get to have your cake and eat it, you get to be both famous and rich , but in the world of entrepreneurship , very very few entrepreneurs are both rich and famous, and when I mean very few, it’s just Jeff Bezos, Zuckerberg , Elon. There are no Robert Downey jnr in Entrepreneurship, there is only iron and hard steal that you have to chisel through. I think the reason people want to be famous or well known entrepreneurs is because they haven’t understood their business models and what it will take for those models to work.

You see 2 years ago if you had said to me , Abed are you a fan of B-C or B-B models , I would have thought you are talking about… well hmm, all guys know what I was thinking here. You see I was not familiar with this lingo of business to consumer or Business to business models, however I have come to believe this is the epicenter of all business and why businesses fail. Very few people apply their minds to ensuring they not only understand their business model but understand who the customer is for their product and service.

Quick summary, business to consumer models , you sell your product directly to a consumer who uses and enjoys the benefit of your service or product. Business to business models, your customer is typically another business here. Examples here are , when you buy clover milk from Pick and Pay, pick and pay is in the business to consumer market , they are selling a product directly to you , the end consumer of the carton of milk. When clover sells the milk to pick and pay, they are in a Business to business model , their customer is Pick and Pay, even further , a farmer who produces the milk is also in the business to business market, he sells his milk to clover , if you want to take it a little further , the packaging company , the delivery company for the milk , the company that adds preservatives, all these businesses are operating a business to business model with clover or pick n pay being their customers.

The problems with a business to consumer model , in my minds eye are simple , you have to build a brand , which means years of spending advertising budget, people need to know you exist , you need social media campaigns, billboards , google ad words, you need to become famous. you see business to consumer businesses are hard , no one tells you that, they are driven by volumes because mostly you are targeting a larger number of consumers. These markets also very competitive , any product that you can think of that is consumer facing has fierce competition from established monopolies and oligopolies, 98% of the time you cannot compete with their marketing teams, budgets , and balance sheets and their bloody bill boards, imaging launching a retail bank currently with all of Absa’s billboards, I swear next week they doing a color run for South Africa and they painting the sky red, I digress.

What fascinates me the most though is that when people quit their jobs or think of entrepreneurship they want to do a business to consumer model, they want to open a restaurant , a hair and beauty salon , a food product business for consumers, a bar, then next cool Chesa Nyma , these are the businesses that I call famous businesses . I know this because I too was a part of this. (Nothing wrong with these businesses but know the challenges upfront)

You see at the braai , everyone knows the guy who is in a business to consumer business , if I asked everyone who is the owner of Saint , Gemelli , 75% of the people would know the answer , but if I asked you who is the biggest tooth pick provider to all the restaurants in the country you don’t know that man or lady, yet I can tell you right now without even meeting the owner they are richer than any restaurant owner. Who is the biggest supplier in the country of those small sugars and salts you have at all restaurant tables ? I could go one.

You see no one will ever invite the guy who manufactures tooth picks and straws to come give a talk at the next Finance Indaba , they would rather have a business to consumer entrepreneur , why? Because they famous right ? We all know them , they on TV, their brands are in our face , you see while your favorite chef and restaurant struggles to pay the rent and employees , he is still sending the R3000 per month to the tooth pick manufacture, here is the secret , so are all the other 200 restaurants in that area , that your favorite chef and restaurant has to compete with , because he is in a b-C market , and when the restaurant closes down eventually , the tooth pick manufacturer is not worried, soon a new tenant will take up the lease to attempt his business to consumer restaurant business and continue to send him the R3000 that the previously failed restaurant was sending. All the while , you and I haven’t heard of this tooth pick manufacturer.

Don’t get me wrong, business to consumer markets can work , there are many examples of successful restaurants , “Uber of “ businesses , nail and beauty bars etc, but they are hard core , this does not mean that business to business markets are easy , but you generally don’t need a lot of clients in the business to business space, the tooth pick manufacture needs 20 restaurants and he is a R60-80k Business per month, the restaurant needs to seat hundreds of clients per day to get to the R80k, he has to sell his product hundred of times to achieve the result of the business to business model. And he also has to deal with the patrons who buy 1 coffee and sits there for hours for the free WiFi . I have done this plenty times.

Business to business has its own challenges too, the sales cycles are longer , you need to demonstrate problem solving solutions rather than experiences and features such as  in the consumer markets , however it’s bigger Cheques and more sustainable earnings because generally its contract driven. You cannot contract your patrons to have dinner at your your restaurant every night, yet the tooth pick and straw manufacturer have retainer agreements with the restaurant.

You see I have boiled it down to this , the human experience wants to be famous , we want to be invited to speak, as a guest speaker , we want to be Zuckerberg , we want to be in the front. The older I get I want nothing to do with this , I have learnt the biggest secret , the most successful business owners are the ones we haven’t heard off mainly because they don’t service a consumer market , you see we all have heard of Roy Croc , and Mac Donald’s , but if I woke you up in the middle of the night and said “who is mac Donald’s biggest lettuce supplier , or tomato supplier “ you wouldn’t know , because they are not famous , they are in a business or business model but you can find them on Malibu beach guaranteed.

This is a long way of saying, understand the challenges of the markets your operate in , are you a consumer facing business or business facing , and do you understand the pros and cons of each? I certainly don’t have a blue print , but I think it’s important to know upfront what you in for

As a true test always ask yourself when you wear your favorite Levi’s jeans tomorrow , I wonder who provides Levi’s with their buttons for their jeans, yip thought so, you don’t know, but that owner is sitting somewhere on an island.

Do you want to be famous or do you want to be rich ? Go and find youth tooth pick solution.

8 Ways to Make Money as a Blogger

That aren’t ads or affiliate links in your blog.

Photo by Kaitlyn Baker on Unsplash

There are many ways you can make money from your blog.

The main ones we hear about include having ads on your blog, using affiliate links, and upselling your readers whatever you’re trying to sell, such as creating a blog post about the top 5 best ways to market your ebook and then having an ad at the bottom for an inexpensive workbook or guide with more book marketing tips or your own ebook.

You can also be part of Medium’s Partner Program and make money monthly based on how many claps your stories get.

But what about using your blog as a jumping-off point, as opposed to the blog earning money?

HERE ARE 8 WAYS TO MAKE MONEY AS A BLOGGER:

  • Become a freelance blogger. There are many companies who need regular blogs written for their sites, and many digital marketing agencies who use freelancers to write blogs for their clients. You can also write and contribute articles to online publications who pay. Here’s a list of more than 100 sites that pay for articles from FreelanceWritingGigs.com.

Being a freelancer doesn’t mean you have to do everything (copywriting, editing, etc.) or do it full-time. You can pick up a client here and there or contribute an article now and then as you want. It can be a great way to earn a little extra money without committing to it full-time. If you want to find clients without cold messaging, you can check out one of the sites I use sometimes, ProBlogger.

  • Use your blog content to write a book. If you write about one subject or topic often, consider packaging your blogging content into a manuscript and expanding on the information, giving examples, and adding more. You can easily use your blog content as the starting point of a book!

Having a published book gives you more authority and perceived credibility and positions you as a subject-matter expert. This will open up a new revenue stream and will also give you more opportunities for getting clients and raising your prices.

  • Start a podcast. You can start a podcast for free on platforms like Anchor Stitcher, SoundCloud, Buzzsprout and many more. Your podcast can have sponsors and ads on it, generating revenue, and you can get it on all the main streaming services. You can also put it on your website as an additional service.

Some podcasts even charge guests a fee to be featured when they get large enough, giving you a larger potential to make money. Also, podcasts open you up to an even bigger potential audience.

  • Start a YouTube channel. Similar to starting a podcast, you can turn your blogs into video and give your stories new life with audio and video. You can add graphics, text, pictures, do screensharing presentations, interviews, and much more.

YouTube ads bring in money as your channel grows and you can choose a ton of different search terms. You’re also able to edit your titles and descriptions if you need to as you go.

  • Create a free or inexpensive webinar. If you are an expert in something and use your blog to teach others, think about offering a free or cheap webinar to teach them in a different format.

Your webinar will also act as a lead generator, gathering emails and names of people who watch it, giving you warm leads to sell them your book, advertise your podcast, send newsletters, and potentially turn them into clients.

  • Create an online course. You may not want to do a short webinar or perhaps what you teach is too intricate or technical to teach in a shorter format like that. You can always jump into a longer course to teach groups. You have the option of creating and marketing it yourself (it’s tough but doable) or using an existing platform like Udemy or Coursera, where you can create a course or five and put it on their platform, they will help with marketing and promoting your course and pay you based on how many students enroll.

Many people have been successful in creating a passive income on sites like Udemy after creating a structured, polished, informative course. I’ve been looking more and more into this and check out this Quora thread about Udemy and earnings.

  • One on one or group coaching. If you are teaching people anything, you can offer coaching to help them. Many people I know had never heard of a book coach until I decided to become one.

If what you write about is applicable, offering coaching for individuals or groups (for example, business or life coaching or social media marketing) or consulting with companies (for example, if you’re an expert in data security or marketing or sales or efficiency). Almost anything can be made into a coaching situation, as everyone has some expertise to share and many people want or need to learn!

  • Become a paid speaker. If you have a couple of topics you can speak on well and have a blog with followers and readers, you can use your blog as a launchpad for speaking gigs.

Most people don’t realize this, but if you want speaking gigs, most of the time the gigs don’t come to YOU, you go find THEM and pitch yourself to the organizers as a speaker. So, you would look for conferences, conventions, or school events that you think you’d be a good fit for, then reach out to the organizers to introduce yourself and the topics you speak on. They would check out your blog or podcast or whatever you provide them and decide if you’d be a good fit for their event. Similar to how you have to pitch your stories to a publication, you pitch yourself to speaking opportunities.

THERE YOU HAVE IT.

Eight different ways you can use your experience as a blogger to launch into different money-making opportunities.

What did I miss? Are there any not on here that you do and make money from? Let us know in the comments!

Jyssica Schwartz: Entrepreneur, writer, editor, book coach, cat lover, weirdo, optimist. Author of “Write. Get Paid. Repeat.” and “You Are Not Alone.”