<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Paolo Forgia on Medium]]></title>
        <description><![CDATA[Stories by Paolo Forgia on Medium]]></description>
        <link>https://medium.com/@paolowalter.forgia?source=rss-55cb0a02ec6e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2p-dyeujojs4UpkJypkSPQ.png</url>
            <title>Stories by Paolo Forgia on Medium</title>
            <link>https://medium.com/@paolowalter.forgia?source=rss-55cb0a02ec6e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:02:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@paolowalter.forgia/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to easily validate forms with Vest: a beginner’s guide]]></title>
            <link>https://medium.com/@paolowalter.forgia/how-to-easily-validate-forms-with-vest-a-beginners-guide-72068cf0536b?source=rss-55cb0a02ec6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/72068cf0536b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[vest]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Paolo Forgia]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 06:52:41 GMT</pubDate>
            <atom:updated>2025-04-15T06:52:41.884Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eY7O7cQAot7yr5eccm2fqg.png" /></figure><h3><strong>Introduction to VEST.js</strong></h3><p>Form validation is a crucial part of modern web development but managing it can quickly become complex. <strong>VEST.js </strong>offers a simple, declarative solution that makes form validation easy to define, test, and maintain.</p><p>In this post, we’ll explore how VEST.js streamlines form validation, allowing developers to handle errors with minimal boilerplate.</p><h3><strong>Prerequisites</strong></h3><p>In this blog we will use <a href="https://react.dev/">React</a>, <a href="https://mui.com/">Material UI</a> as our components library, and <a href="https://www.typescriptlang.org/">TypeScript</a>.</p><p>We will start from an existing project and build on it to showcase all that Vest is capable of.</p><ul><li>Check the project out at <a href="https://github.com/PaoloForgia/ReactValidationWithVest">https://github.com/PaoloForgia/ReactValidationWithVest</a>,</li><li>open ‘ReactValidationWithVest_initial’, and</li><li>run ‘npm install’ to install all the dependencies, after that</li><li>run ‘npm run dev’ to launch the application.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*m_tJFEretszB_k0qgeiEYw.png" /><figcaption>Running npm run dev in the console</figcaption></figure><h3><strong>Before we start</strong></h3><p>Let’s quickly look at what’s inside the current project. The application simply renders a ‘&lt;RegistrationForm /&gt;’ that contains the fields that are visible in the page; inside, we have one input for each field we are expecting: username, email, password and the password confirmation, and the submit button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*XPB8fFc7-c29tWRSkOS2yg.png" /><figcaption>The application with all the components</figcaption></figure><p>The input will have different styling that we pass: default, success, warning, or error, and we can pass a ‘message’ to display under the input field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*G5bRpYJP_hAyly54CuSiVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*4qFUCthH3DFfeCU1GZB-aw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*TqwVgWFArS0rIQhR4aDKTw.png" /><figcaption>From left to right: success, warning and error</figcaption></figure><h3><strong>Vest syntax is Jest-like</strong></h3><p>If you are familiar with the popular testing framework <a href="https://jestjs.io/">Jest</a>, the syntax from Vest will look very familiar.</p><p>If we wish to test that the ‘username’ is defined, in Jest we would write something like this:</p><pre>describe(&quot;registration_form&quot;, () =&gt; {<br>  test(&quot;username&quot;, () =&gt; {<br>    expect(username).toBeDefined();<br>  });<br>});</pre><p>Changing a few keywords will make our test become a function to enforce form validation.</p><ul><li>We are no longer describing something but creating the Vest suite.</li><li>In the test we need to specify the validation message.</li><li>And we are not expecting a result anymore, but we are enforcing a condition.</li></ul><p>And this is the result:</p><pre>import { create, enforce, test } from &quot;vest&quot;;<br><br>create(&quot;registration_form&quot;, ({ username }: User) =&gt; {<br>  test(&quot;username&quot;, &quot;username is required&quot;, () =&gt; {<br>    enforce(username).isNotBlank();<br>  });<br>});</pre><h3><strong>Let’s make the forms work</strong></h3><p>If you tried playing with the page, you may have noticed that you cannot even type in the forms, so let’s fix this.</p><p>We want our input values to be stored in an object that will represent our user: we create a ‘type User’:</p><pre>export type User = {<br>  username?: string;<br>  email?: string;<br>  password?: string;<br>  passwordConfirmation?: string;<br>};</pre><p>To handle the change from the input, we can define a <a href="https://react.dev/reference/react/hooks">hook</a> that will store the user object and handle the ‘onChange’ event.</p><pre>const useRegistrationForm = () =&gt; {<br>  const [form, setForm] = useState&lt;User&gt;({});<br><br>  const onChange = (value: string, name: string) =&gt; {<br>    const nextState = { ...form, [name]: value };<br>    setForm(nextState);<br>  };<br><br>  return { form, onChange };<br>};<br><br>export default useRegistrationForm;</pre><p>In ‘RegistrationForm’ we can import this hook and use it.</p><pre>const { form, onChange } = useRegistrationForm();<br><br>[…]<br><br>  &lt;Input<br>    label=&quot;Username&quot;<br>    name=&quot;username&quot;<br>+   value={form.username}<br>+   onChange={onChange}<br>  /&gt;</pre><p>Add the ‘value’ and the ‘onChange’ for all the input and now you can type in the form.</p><h3><strong>Add Vest validation to the mix</strong></h3><p>We can re-create the Vest suite that we saw in the example before to prevent the username being empty.</p><pre>export const suite = create(&quot;registration_form&quot;, ({ username }: User) =&gt; {<br>  test(&quot;username&quot;, &quot;username is required&quot;, () =&gt; {<br>    enforce(username).isNotBlank();<br>  });<br>});</pre><p>To execute the validation inside ‘useRegistrationForm’, we import the ‘suite’ created above and add the following line.</p><pre>  const onChange = (value: string, name: string) =&gt; {<br>    const nextState = { ...form, [name]: value };<br>    setForm(nextState);<br>+   suite(nextState);<br>  };</pre><p>And to display the message returned by the validation we need to call the ‘suite’ again and get the message.</p><pre>&lt;Input<br>   label=&quot;Username&quot;<br>   name=&quot;username&quot;<br>   value={form.username}<br>   onChange={onChange}<br>+  message={suite.getMessage(&quot;username&quot;)}<br>/&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*S5KCd2NaVPu6r0TXVZwVKQ.png" /><figcaption>Input component with the message displayed</figcaption></figure><p>If we type something and then delete it, we can see the message ‘username is required’ displayed.</p><h3><strong>Showing the error state</strong></h3><p>To access the status of the current field, Vest offers some <a href="https://vestjs.dev/docs/writing_your_suite/accessing_the_result">methods to interact with the data</a>.</p><p>In our case, we are interested in whether our field is in error state, in warning state (which we will discuss later), or successful.</p><pre>const getState = (fieldName: string) =&gt; {<br>  if (suite.hasErrors(fieldName)) return &quot;error&quot;;<br>  else if (suite.hasWarnings(fieldName)) return &quot;warning&quot;;<br>  else if (suite.isValid(fieldName)) return &quot;success&quot;;<br>};<br><br>[…]<br><br> &lt;Input<br>   label=&quot;Username&quot;<br>   name=&quot;username&quot;<br>   value={form.username}<br>   message={suite.getMessage(&quot;username&quot;)}<br>+  state={getState(&quot;username&quot;)}<br>   onChange={onChange}<br> /&gt;</pre><p>The input will now correctly display the colour based on the status, as well as the message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*WL3f8yiYkuWQPFMQmqLE8g.png" /><figcaption>Input component with the error mesasage</figcaption></figure><h3><strong>Let’s talk about the warning state</strong></h3><p>Our username field has improved but is not yet complete. I want to add two more checks: the username has to be longer than 3 characters, and also, I want to make sure that the username I want to use is not already used by someone else.</p><pre>test(&quot;username&quot;, &quot;must be at least 3 characters&quot;, () =&gt; {<br>  enforce(username).longerThanOrEquals(3);<br>});<br><br>test(&quot;username&quot;, &quot;username already taken&quot;, () =&gt; {<br>  const exists = doesUsernameExist(username);<br><br>  enforce(exists).isFalsy();<br>});</pre><p>To check if the username exists, I would normally call our API to see if it’s already used. In this case, I have a simple function ‘doesUsernameExist’ to fake that behaviour but without it calling any API.</p><p>In my case the username ‘paolo’ is already being used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*WUhAR3amxlHQTNIjvok-PQ.png" /><figcaption>Input component with username already taken error</figcaption></figure><p>However, displaying it as an error seems a bit excessive: we can make it a warning by just adding ‘warn()’ to our validation.</p><pre> test(&quot;username&quot;, &quot;username already taken&quot;, () =&gt; {<br>+  warn();<br>   const exists = doesUsernameExist(username);<br><br>   enforce(exists).isFalsy();<br> });</pre><h3><strong>Testing more fields</strong></h3><p>The username is finally done; we can now add other tests. Let’s continue with the email.</p><p>To enforce the validation on emails, we need to import ‘vest/enforce/email’ to have access to the ‘isEmail’ validator.</p><pre>import &quot;vest/enforce/email&quot;;<br><br>export const suite = create(&quot;registration_form&quot;, ({ username, email }: User) =&gt; {<br>  [...]<br><br>  test(&quot;email&quot;, &quot;email is not valid&quot;, () =&gt; {<br>    enforce(email).isEmail();<br>  });<br>});</pre><p>Let’s now also add the ‘state’ and ‘message’ properties in ‘RegistrationForm’ to see the result.</p><pre>  &lt;Input<br>    label=&quot;Email&quot;<br>    name=&quot;email&quot;<br>    value={form.email}<br>    onChange={onChange}<br>+   state={getState(&quot;email&quot;)}<br>+   message={suite.getMessage(&quot;email&quot;)}<br>  /&gt;</pre><p>The validation works, but <strong>why </strong>are we seeing an error on username too? I don’t want my validation kicking in for username even when I am typing my email.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*S00TpwCIukXwX7lzf6Ib6g.png" /><figcaption>Username and email input components with error message</figcaption></figure><h3><strong>Validate <em>only </em>the correct field</strong></h3><p>To make sure Vest knows which field we are currently working on, we need to pass that information to our suite.</p><pre>import { only } from &quot;vest&quot;;<br><br>export const suite = create(&quot;registration_form&quot;, ({ username, email }: User, fieldName: string) =&gt; {<br>  only(fieldName);<br><br>  […]<br>});</pre><p>We add another parameter which is the ‘fieldName’, and we call ‘only’ from Vest to make sure to only validate that field.</p><p>And in our hook ‘useRegistrationForm’ we pass the field name.</p><pre>const onChange = (value: string, name: string) =&gt; {<br>  const nextState = { ...form, [name]: value };<br>  setForm(nextState);<br>+ suite(nextState, name);<br>};</pre><h3><strong>Validate fields that depend on each other</strong></h3><p>Our validation suite is shaping up nicely; we need validation to add the password and password confirmation. We will add a couple of simple validation rules: password must be longer than 5 characters, and the password confirmation must match the password.</p><pre>test(&quot;password&quot;, &quot;must be at least 5 characters&quot;, () =&gt; {<br>  enforce(password).longerThanOrEquals(5);<br>});<br><br>test(&quot;passwordConfirmation&quot;, &quot;must match password&quot;, () =&gt; {<br>  enforce(passwordConfirmation).equals(password);<br>});</pre><p><strong>Note</strong>: remember to add ‘state’ and ‘message’ properties in ‘RegistrationForm’ to see the result.</p><p>With this, we encounter a problem, since we can make ‘passwordConfirmation’ match the password and later change the password, resulting in a situation like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*87DGcyTNUCcGumkAawuxzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*ld2x78Byzw3oUuxQ7GCqZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*l0rTTE1yneJdiRfzxD68rQ.png" /><figcaption>Type the password, then the password confirmation, then change the password again</figcaption></figure><p>To avoid this, we can make use of ‘include()’ to include in the validation ‘passwordConfirmation’ when ‘password’ is changed.</p><pre>import { include } from &quot;vest&quot;;<br><br>export const suite = create(<br>  &quot;registration_form&quot;,<br>  ({ username, email, password, passwordConfirmation }: User, fieldName: string) =&gt; {<br>    only(fieldName);<br><br>+   include(&quot;passwordConfirmation&quot;).when(&quot;password&quot;);<br><br>   […]<br>  },<br>);</pre><h3><strong>One last thing</strong></h3><p>Our validation suite is finally finished. You might have noticed, however, that the ‘Register’ button was enabled all the time, even when the form contained invalid data.</p><p>To enable the button only when everything is acceptable, we can use ‘suite.isValid()’.</p><pre>&lt;Button label=&quot;Register&quot; disabled={!suite.isValid()} /&gt;</pre><h3><strong>Conclusion</strong></h3><p>As you saw, Vest provides a simple yet powerful solution for handling form validations with ease and reliability. And the best thing is that, even though we didn’t mention it in this post, Vest can be used for <a href="https://vestjs.dev/docs/server_side_validations">server side validation</a> as well.</p><p>You can find the fully working prototype here: <a href="https://github.com/PaoloForgia/ReactValidationWithVest">https://github.com/PaoloForgia/ReactValidationWithVest</a>.</p><p>Make sure you also check out <a href="https://vestjs.dev/">https://vestjs.dev/</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72068cf0536b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>