About The Writer

Kristofer Selbekk is the React lead at Bekk, and has labored on quite a few giant initiatives for the final 6 years. He hosts a beer primarily based programming meetup, tries to …
Extra about Kristofer

In the event you’ve been following alongside this little article collection, you’ve now realized methods to put collectively your very personal validation library. It might probably deal with nearly any problem you may throw at it, and it even helps out with accessibility issues! Its solely downfall is that it sucks to work with.

Yep, that’s proper. The person expertise from a developer viewpoint is critically missing. We don’t get any useful warnings once we misspell phrases, misuse APIs or, nicely, something, actually!

This text will information you thru how one can enhance the developer expertise of your validation library — or any library for that sake.

Beginning Out

Because the final a part of this text, we’ve pulled out all library code into its personal recordsdata. Check out the CodeSandbox demo to see what we’re beginning out with.

Comfort Capabilities

We would like our library to be so simple as potential to make use of for the commonest instances. A method to transfer in direction of that objective is so as to add handy utility capabilities for sure performance.

One such function could possibly be to verify if our type is legitimate — that’s, if all error messages are null. That is one thing you sometimes verify in your onSubmit handler, but it surely could possibly be helpful in your render-method too. Let’s implement it!

const isFormValid = useMemo(
  () => Object.values(errors).each(error => error === null), 

We’ll present this flag in our onSubmit type handler, in addition to in our render methodology.

There are a lot extra of those that could possibly be written, however I’ll let that be an train for the reader.

Growth Warnings And Invariants

One in every of React’s biggest options is its many beneficial console warnings whereas creating. We should always present the identical kind of high quality to our customers as nicely.

To get began, we’ll create two capabilities — warning for logging warnings to the console, and invariant for throwing an error — each if a given situation just isn’t met.

perform warning(situation, message)  situation) 

  console.warn('useValidation: ' + message);

perform invariant(situation, message) 

You need to use invariant if the error goes to crash your library (or render it ineffective), and warning for unhealthy practices or different recommendation.

When To Warn

Deciding when to warn is fairly essential. Too many, and also you’re simply annoying. Too few, and also you let important bugs ship to manufacturing. Due to this fact, we should be good with our warnings.

Since our library accepts a pretty big configuration object, it is sensible to validate this by some means — at the very least whereas creating. We might remedy it by utilizing a sort system like TypeScript or Stream, however that excludes all common ol’ JavaScript customers.

As an alternative, let’s create a runtime schema checker, the place we validate that the config incorporates the proper fields, and print related warnings.

perform validateConfigSchema(config) 

We might most likely go on doing this for some time if we needed to spend the time. And you need to! It’s a good way to enhance the developer expertise of your app.

You don’t must be writing these by hand, nevertheless. There’s a browser-port of the favored object schema validation library joi that would assist out with making a very nice runtime validation verify. Additionally, as beforehand talked about, a sort system would assist catch configuration errors at compile time for the customers that use that kind system.

Permit For Flexibility

A superb developer expertise is largely not getting in the best way of the builders. Let’s have a look at just a few methods we will enhance that have.

Compose Conflicting Props

First, our prop getters apply some props to our inputs and kinds that may be unintentionally overridden by our customers. As an alternative, let’s add a prop override object to our prop getters, which is able to compose any conflicting props collectively.

Right here’s how we will implement this in our getFieldProps:

getFieldProps: (fieldName, overrides = ) => ({
  onChange: e => ,
  onBlur: e => ,
  identify: overrides.identify || fieldName,
  worth: state.values[fieldName] || '',

An identical method could be adopted in getFormProps.

Assist Keep away from Prop Drilling

Some kinds is likely to be giant and break up up into a number of parts. As an alternative of constructing our customers’ drill props down the tree, we should always present a context. This fashion, they will entry all of the stuff we return from our customized hook wherever within the tree beneath.

First, let’s create a ValidationContext with React’s createContext methodology:

export const ValidationContext = React.createContext();

Subsequent, let’s create a part ValidationProvider, that gives all of the values from the useValidation hook in context as an alternative:

export const ValidationProvider = props => ;

Now, as an alternative of calling useValidation instantly, we’d wrap our type in a ValidationProvider part, and get entry to the validation props (getFormProps, errors and so on) by use of the useContext hook. You’d use it like this:

Import React,  from 'react';
import  from './useValidation';

perform UsernameForm(props) 

This fashion, you get the very best of each worlds! You get a easy hook for these easy situations, and also you get the flexibleness you want for these complicated components.

Documentation Is Key 🔑

Each time I’m utilizing a library I didn’t write myself, I like nice documentation. However what do you have to deal with, and the place do you have to doc?

A primary step must be to place collectively a easy to grasp README, with essentially the most fundamental utilization examples available. Andrew Healey wrote an incredible piece on methods to write a very good README, which I extremely suggest you learn.

While you’ve created a very good README to get folks going, a documentation web site is likely to be a good suggestion. Right here, you may put a extra in-depth API documentation, recipes for typical use instances and a very good ol’ FAQ.

There are nice instruments on the market for producing documentation web sites. My favourite is docusaurus from Fb (humble brag: we used it when creating the create-react-app web site), however there are a number of good alternate options on the market.

We’re not going to undergo methods to write good documentation on this article. There are a number of good articles on the market — even a group known as “Write the Docs”. They’ve written an excellent information to how one can get began with writing nice documentation.


Via this text collection, we’ve created a fairly first rate validation library. It has a fairly easy API, flexibility for whenever you want it, a very good developer expertise, and a variety of fairly dank options.

We’ve gone by way of how we carried out issues step-by-step, and I hope you bought a deeper understanding of how one can make your personal library, and the way you make it one thing folks would love to make use of.

Please let me know within the feedback what you suppose, and if there have been some components you bought caught on or had a tough time understanding. I’ll attempt my greatest to replace the article as suggestions trickles in.

To finish this text off — right here’s the ultimate model:

Thanks for studying!

(dm, yk, il)