<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Form validations - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Form validations - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 14 May 2026 22:44:23 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/form-validations/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Validate Forms in React and React Native Using Yup and Formik ]]>
                </title>
                <description>
                    <![CDATA[ Validation is a key part of development, regardless of what programming language you’re writing. Developers should always be validating user input, API parameters, and retrieved values. One of the most common elements where you’ll need to apply user ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-how-to-validate-user-input/</link>
                <guid isPermaLink="false">66bb889bc32849d18c5cdca7</guid>
                
                    <category>
                        <![CDATA[ Form validations ]]>
                    </category>
                
                    <category>
                        <![CDATA[ forms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Grant Riordan ]]>
                </dc:creator>
                <pubDate>Mon, 24 Jun 2024 19:51:14 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/1080_Template.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Validation is a key part of development, regardless of what programming language you’re writing. Developers should always be validating user input, API parameters, and retrieved values.</p>
<p>One of the most common elements where you’ll need to apply user input validation is via a form. This could be a user sign up form, a contact us form, or a simple questionnaire.</p>
<h2 id="heading-outcomes-of-the-tutorial">Outcomes of the Tutorial</h2>
<p>By the end of this article , you will be able to:</p>
<ul>
<li>Understand common issues with form validation.</li>
<li>How to utilise the Yup schema validation library alongside the Formik form library.</li>
<li>How to build a form in React with full validation (same principles apply for React Native, with different component syntax).</li>
</ul>
<h2 id="heading-contents">Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-validation">What is Validation</a>?</li>
<li><a class="post-section-overview" href="#heading-the-object-to-be-validated">The Object to Be Validated</a></li>
<li><a class="post-section-overview" href="#heading-introducing-yup-and-formik">Introducing Yup and Formik</a></li>
<li><a class="post-section-overview" href="#heading-how-to-add-validation-to-a-form">How to Add Validation to a Form</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-what-is-validation">What is Validation?</h2>
<p>Validation is defined as:</p>
<blockquote>
<p><em>the action of checking or proving the validity or accuracy of something.</em></p>
</blockquote>
<p>But what does that mean in computer speak? This could be a multitude of things, but the premise still stands. You could be validating a variable value or an object against a pre-determined set of rules or regulations.</p>
<p>Examples of validation rules could be:</p>
<ul>
<li>Password must be at least 8 characters and contain a special character.</li>
<li>Username must be unique.</li>
<li>Date of birth must be received as a string, in a particular format, for example ISO8601</li>
</ul>
<p>Let’s use the example of a user registration form on a website. </p>
<h2 id="heading-the-object-to-be-validated">The Object to Be Validated</h2>
<p>The form will comprise of several inputs to form a <code>UserRegistration</code> object. Like so‌:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">interface</span> UserRegistration {
  firstName: <span class="hljs-built_in">string</span>;
  surname: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  dob: <span class="hljs-built_in">string</span>;
}
</code></pre>
<p>Above is an interface (contract) for a <code>UserRegistration</code> object. It simply defines some key user information which needs to be collected, with all values being a <code>string</code> value.</p>
<p>While languages like TypeScript are useful for ensuring that we pass the correct types to functions throughout our application, they do not inherently validate the actual content or values within those types. TypeScript guarantees that a variable is of a specific type, such as a string or a number, but it does not verify if the content of that string or number meets specific criteria or constraints.</p>
<h3 id="heading-what-if-we-didnt-validate-the-values">What If We Didn't Validate the Values?</h3>
<p>Ok, before we move onto how to validate, let's look at what could happen if we don't validate.</p>
<p>Without validation, a user could input the following values:</p>
<p><strong>Firstname</strong>: 1231301‌<br>‌<strong>Surname</strong>: Hello##test_101‌<br>‌<strong>Email</strong>: user_123@@email.to@.com‌<br>‌<strong>DoB</strong>: 10+12+1909</p>
<p>These values may <strong>seem</strong> perfectly acceptable, and your front end might allow them to be submitted without any issues. And the API will likely accept these values initially. </p>
<p>But when the API attempts to parse these values (converting) during the request processing, it will encounter errors and fail to process the request correctly.</p>
<p>There are several negative consequences to this approach:</p>
<ol>
<li><strong>Increased Server Load</strong>: The front end is making multiple invalid requests to the server, which unnecessarily strains the server. This extra load could have been avoided.</li>
<li><strong>Potentially Higher Costs</strong>: The cost of handling these invalid requests can increase significantly, depending on your hosting plan and server configuration. Each invalid request consumes server resources that could be used more efficiently.</li>
<li><strong>Poor User Experience (UX)</strong>: Users will likely become frustrated if they repeatedly enter details, submit the form, and then receive error messages indicating that their inputs are invalid. This can lead to a negative perception of the application.</li>
</ol>
<p>To mitigate these issues and reduce the number of invalid requests, we can implement 'client-side validation' to ensure that the data meets the required criteria before sending the API request.</p>
<h2 id="heading-introducing-yup-and-formik">Introducing Yup and Formik</h2>
<p>Yup and Formik are both libraries which you can add to any React or React Native application via npm or yarn.</p>
<p>Yup is a schema building library that allows you to build schemas for validation at runtime. It has a plethora of extension functions which can set rulesets, transform values, and return validation messages right out the box.</p>
<p>Let's take a look at an example of a Yup schema for our user form:‌</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> Yup <span class="hljs-keyword">from</span> <span class="hljs-string">'yup'</span>;

<span class="hljs-comment">// If using Typescript, you can utilise a wrapper function to enforce strict typing</span>

<span class="hljs-keyword">const</span> createYupSchema = &lt;T <span class="hljs-keyword">extends</span> <span class="hljs-built_in">object</span>&gt;(schema: Yup.ObjectSchema&lt;T&gt;): Yup.ObjectSchema&lt;T&gt; =&gt; schema;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> userFormSchema = createYupSchema&lt;UserInput&gt;(
  Yup.object().shape({
    firstname: Yup.string().required(<span class="hljs-string">'First name is required'</span>),
    surname: Yup.string().required(<span class="hljs-string">'Surname is required'</span>),
    email: Yup.string().email(<span class="hljs-string">'Invalid email format'</span>).required(<span class="hljs-string">'Email is required'</span>),
    dob: Yup.string().required(<span class="hljs-string">'Date of Birth is required'</span>),
  })
);

<span class="hljs-comment">// JS Version</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> validationSchema = Yup.object({
  firstname: Yup.string().required(<span class="hljs-string">'First name is required'</span>),

  surname: Yup.string().required(<span class="hljs-string">'Surname is required'</span>),
  email: Yup.string().email(<span class="hljs-string">'Invalid email format'</span>).required(<span class="hljs-string">'Email is required'</span>),
  dob: Yup.date().required(<span class="hljs-string">'Date of Birth is required'</span>)
});
</code></pre>
<p>We're creating a Yup object (schema) which contains all of our Keys for our UserInput interface.</p>
<h3 id="heading-schema-parts">Schema Parts:</h3>
<ul>
<li>key: the key which will be used later for the name of our element (as we're using TypeScript, this needs to match the object key name).</li>
<li>ruleset: for all keys, apply a ruleset. A ruleset must start with a typing declaration, that is <code>Yup.string()</code> or <code>Yup.number()</code> and so on. You can then chain your other validation functions. </li>
</ul>
<p>Using TypeScript ensures that we match the schema type to our interface types.</p>
<p>For example, if we try and do this:</p>
<pre><code class="lang-ts">firstname: Yup.date().required();
</code></pre>
<p>it will throw a TypeScript error complaining that <code>firstname</code> cannot be validated as if it was a date, as the type of firstname is a <code>string</code>.</p>
<h3 id="heading-how-to-add-validation-to-a-form">How to Add Validation to a Form</h3>
<p>This is where our Formik library comes in and makes things much easier than validating a form and implementing error handling manually.</p>
<p>Formik is a library which encapsulates a <code>&lt;Form/&gt;</code> component. It allows us to create richer forms in React and React Native, giving us access to features like form state, error handling, validation, and processing of form submissions much more efficiently.</p>
<p>You can access a pre-built version of a UserForm utilising Yup, Formik, and React (Vite) at my GitHub <a target="_blank" href="https://github.com/grant-dot-dev/fcc-yup-schema-validation">here</a>. Simply clone the GitHub repository and follow the README.md instructions. ‌</p>
<pre><code class="lang-tsx">&lt;Formik
        initialValues={initialValues}
        validationSchema={userFormSchema}
        onSubmit={onSubmit}
      &gt;
        {({ isValid, dirty, isSubmitting }) =&gt; (
          &lt;Form&gt;
            &lt;div className="form-control"&gt;
              &lt;label htmlFor="firstName"&gt;First Name&lt;/label&gt;
              &lt;Field type="text" id="firstName" name="firstName" /&gt;
              &lt;ErrorMessage name="firstName" component="div" className="error" /&gt;
            &lt;/div&gt;

            &lt;div className="form-control"&gt;
              &lt;label htmlFor="surname"&gt;Surname&lt;/label&gt;
              &lt;Field type="text" id="surname" name="surname" /&gt;
              &lt;ErrorMessage name="surname" component="div" className="error" /&gt;
            &lt;/div&gt;

            &lt;div className="form-control"&gt;
              &lt;label htmlFor="email"&gt;Email&lt;/label&gt;
              &lt;Field type="email" id="email" name="email" /&gt;
              &lt;ErrorMessage name="email" component="div" className="error" /&gt;
            &lt;/div&gt;

            &lt;div className="form-control"&gt;
              &lt;label htmlFor="dob"&gt;Date of Birth&lt;/label&gt;
              &lt;Field type="date" id="dob" name="dob" /&gt;
              &lt;ErrorMessage name="dob" component="div" className="error" /&gt;
            &lt;/div&gt;

            &lt;button type="submit" disabled={isSubmitting || !isValid}&gt;Submit&lt;/button&gt;
          &lt;/Form&gt;
        )}
      &lt;/Formik&gt;
</code></pre>
<p>In this code, we've utilsed the <code>&lt;Formik/&gt;</code> library component, which wraps around our standard <code>&lt;Form/&gt;</code>  element. We pass the following properties to the component:</p>
<ul>
<li><code>**initialValues**</code> – these are the required initial values of your form (that is when the form renders what values your inputs will have).‌ </li>
<li><strong><code>validationSchema</code> –</strong> this is probably the most important for this tutorial. Bear in mind this is an optional property, as it's not needed to utilise the <code>&lt;Formik/&gt;</code> component, but for any validation it is. ‌<br>‌‌<br>‌We're going to import our <code>userFormSchema</code> we created in the previous step. This is going to tell the form, when validating inputs within this form utilise these schemas. ‌</li>
<li><strong><code>onSubmit</code></strong> – a straightforward function to run on clicking your button / submitting the form. The values of the form will automatically be passed to this function.‌</li>
</ul>
<p>You can wrap the form within a "render prop" function also to utilise some of the exposed props from Formik within your form. You can learn about render props more <a target="_blank" href="https://legacy.reactjs.org/docs/render-props.html">here</a>.</p>
<pre><code class="lang-tsx">{({ isValid, isSubmitting }) =&gt; (
</code></pre>
<p><strong>Note:</strong> This is not required if you don't want to utilise any of the underlying Formik properties within the form itself. You can simply remove and place your opening <code>&lt;Form&gt;</code> tag in its place. ‌<br>‌‌<br>‌But using this render prop allows you to access properties exposed from the Formik component within your <code>&lt;Form/&gt;</code> element. You can see that we are utilising the<code>isValid</code> and <code>isSubmitting</code> properties to control the state of our submit button.</p>
<p>Continuing on with analyzing the code:</p>
<ul>
<li><code>**isValid**</code> – a boolean value which Formik controls based on our schema validation result.</li>
<li><code>**isSubmitting**</code> – A boolean flag indicating if a form is mid-submission. This flag is very useful when wanting to disable a button, to prevent multiple clicks meaning multiple submissions of the form.</li>
</ul>
<p>We can use these values to control the enablement of the submit button like so:</p>
<pre><code class="lang-tsx">&lt;button type="submit" disabled={isSubmitting || !isValid}&gt;Submit&lt;/button&gt;
</code></pre>
<h3 id="heading-input-fields">Input Fields</h3>
<p>It's important to note that when using Formik and Yup, in order for the validation to work, the names of the input fields need to match the Yup schema keys exactly (case sensitive) – otherwise the validation rules won't be registered.</p>
<p><strong>Example:‌</strong></p>
<pre><code class="lang-tsx">&lt;Field type="email" id="email" name="email" /&gt;
&lt;ErrorMessage name="email" component="div" className="error" /&gt;
</code></pre>
<p>We've defined this field is to be used for an email input, and given it the matching <code>name</code> of "email" to our a userFormSchema definition.</p>
<p>Underneath, we code our Formik <code>&lt;ErrorMessage/&gt;</code> component, again passing in the name of '<em>email'</em>, matching our schema. Using the name property we are able to link our input, error message, and validation schemas all together. </p>
<p>If there are any issues with validating the input field, the error message will show any defined error messages – otherwise it will fallback to a default message, e.g "<em>firstname is a required field</em>". This can be less user friendly, so I'd recommend always passing a custom message.</p>
<p>You'll also notice, that when we lose focus or when typing (after first validation has run), it will automatically run validation again. You can overwrite this functionality by setting the <code>validateOnBlur</code> and the <code>validateOnChange</code> flags (true / false).</p>
<p>As an example, it will look like this in its error state.:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/06/image-100.png" alt="Image: Invalid Formik form showing error state" width="600" height="400" loading="lazy">
<em>Image: Invalid Formik form showing error state</em></p>
<p>‌Once we've entered values for all inputs, and our validation has passed (you can see the submit button is now enabled), we can submit.‌</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/06/image-95.png" alt="Image: Valid Formik form showing valid state" width="600" height="400" loading="lazy">
<em></em></p><div id="ember289" class="miw-100 tc bn form-text bg-transparent pr8 pl8 ember-view" data-kg-has-link-toolbar="true" data-koenig-dnd-disabled="true"><div class="koenig-basic-html-input__editor-wrappper"><div class="koenig-basic-html-input__editor __mobiledoc-editor" data-gramm="false" data-kg="editor" data-kg-allow-clickthrough="" data-placeholder="Type caption for image (optional)"><p><em>Image: Valid User form with enabled submit button</em></p></div></div></div><p></p>
<h3 id="heading-further-validation-and-formik-features">Further Validation and Formik Features‌</h3>
<p>You've now seen how easy Yup and Formik can make creating a form. It has full validation and even error handling, meaning you can have a fully functioning user friendly form built in just a few minutes.</p>
<p>But what if you want to add more complex validation to a much larger / complicated form? Well, let's look at an example:</p>
<p>Let's say we want to validate that the date of birth provided ensures that the user is over the age of 18. We will also add a password field, which will have rules of:</p>
<ul>
<li>minimum of 6 letters</li>
<li>contain a number</li>
<li>contain a special character</li>
</ul>
<h4 id="heading-dob-extra-requirements">DoB Extra Requirements</h4>
<p>We can do this by chaining the <code>test()</code> function onto the <code>string()</code> function of the dob object within our schema.</p>
<p>The <code>test()</code> function allows us to test against custom logic. Update the <code>dob</code> parameter within the userFormSchema to the following:‌</p>
<pre><code class="lang-ts">dob: Yup.string()
      .required(<span class="hljs-string">'Date of Birth is required'</span>)
      .test(<span class="hljs-string">'is-older-than-18'</span>, <span class="hljs-string">'You must be at least 18 years old'</span>, <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (!value) <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;

        <span class="hljs-comment">// try to parse the value to date</span>
        <span class="hljs-keyword">const</span> parsedDate = parse(value, <span class="hljs-string">'yyyy-MM-dd'</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>());
        <span class="hljs-keyword">if</span> (!isValid(parsedDate)) <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;

        <span class="hljs-keyword">const</span> today = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
        <span class="hljs-keyword">const</span> eighteenYearsAgo = subYears(today, <span class="hljs-number">18</span>);

        <span class="hljs-comment">// check if date provided is before or the same as 18 years ago.</span>
        <span class="hljs-keyword">return</span> parsedDate &lt;= eighteenYearsAgo;
      })
</code></pre>
<p>We now get the following error when trying to submit a date that is less than 18 years ago. ‌</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/06/image-99.png" alt="Image showing Invalid date input field due to failed date validation" width="600" height="400" loading="lazy">
<em>Image: Invalid input field due to failed date validation</em></p>
<h4 id="heading-password-validation">Password Validation</h4>
<p>For the password field validation, we can do something like this:‌</p>
<pre><code class="lang-ts">password: Yup.string()
    .required(<span class="hljs-string">'This field is required'</span>)
    .min(<span class="hljs-number">6</span>, <span class="hljs-string">'Must be at least 6 characters'</span>)
    .matches(<span class="hljs-regexp">/[!@#$%^&amp;*(),.?":{}|&lt;&gt;]/</span>, <span class="hljs-string">'Must contain at least one special character'</span>)
    .matches(<span class="hljs-regexp">/\d/</span>, <span class="hljs-string">'Must contain at least one number'</span>);
</code></pre>
<p>Here we use the <code>matches()</code> function, passing in a regular expression to assert against. You could combine these cases into one regular expression, but the benefit of keeping them separate is it allows you to pinpoint which validation rule is failing. It also allows for a more granular error message and maintenance should the rules change in the future.</p>
<h3 id="heading-other-useful-methods">Other Useful Methods:</h3>
<ul>
<li><code>length()</code> – asserts the length of the string / number</li>
<li><code>positive()</code> – asserts the number type is a positive number</li>
<li><code>email()</code> – asserts that it is a valid email address</li>
<li><code>url()</code>  – asserts that it is a valid URL </li>
<li><code>min()</code> / <code>max()</code> – asserts that the number is at least 'x' and less than 'y'</li>
<li><code>ensure()</code> – transforms <code>undefined</code> and <code>null</code> values to an empty string along with setting the <code>default</code> to an empty string.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>As you can see, the possibilities with Yup are vast. Then combine this with the Formik library, and you can have rich, efficient, and easy to use forms. </p>
<p>This ease of use makes it so much quicker to get a form up and running on your web or mobile application, allowing you to focus on user experience, design, and business logic. </p>
<p>As always feel free to reach and discuss this article with me on <a target="_blank" href="https://x.com/grantdotdev">Twitter</a>, and don't forget to drop me a follow to hear about future articles and dev tips.   </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Client-Side Form Handling with JavaScript – Explained with Example Code ]]>
                </title>
                <description>
                    <![CDATA[ HTML forms are essential components of most websites and web apps. They enable interaction between users and those websites, and are a key concept for web developers to understand.  This comprehensive guide covers various aspects of HTML forms, from ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/form-validation-in-javascript/</link>
                <guid isPermaLink="false">66c72185783c8978e5e7647a</guid>
                
                    <category>
                        <![CDATA[ Form validations ]]>
                    </category>
                
                    <category>
                        <![CDATA[ forms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Samyak Jain ]]>
                </dc:creator>
                <pubDate>Fri, 08 Mar 2024 21:10:35 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/form-handling-in-javascript.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>HTML forms are essential components of most websites and web apps. They enable interaction between users and those websites, and are a key concept for web developers to understand. </p>
<p>This comprehensive guide covers various aspects of HTML forms, from how to create and structure forms to JavaScript interaction and form validation. </p>
<p>Understanding how to work with forms programmatically allows you to validate and capture user input, handle submissions, and enhance the overall user experience. </p>
<p>By following the examples and best practices provided in this guide, you'll be equipped with the knowledge necessary to build robust web forms that enhance user experience and facilitate seamless data collection and submission. </p>
<p>Whether you're a beginner or an experienced developer, this guide serves as a valuable resource for understanding and implementing HTML forms effectively in your web projects. </p>
<h3 id="heading-prerequisites"><strong>Prerequisites:</strong></h3>
<p>A basic understanding of JavaScript fundamentals is recommended to fully comprehend the concepts discussed in this tutorial. Familiarity with HTML forms will also be beneficial for understanding and applying the material covered.</p>
<p>If you're new to JavaScript, it's recommended to acquaint yourself with variables, data types, functions, loops, and basic DOM manipulation techniques before diving into this tutorial. This foundational knowledge will facilitate a smoother learning experience as we explore more advanced topics related to form handling in JavaScript.</p>
<p>Starting Note: For your convenience, all the examples and code discussed here can be accessed on <a target="_blank" href="https://github.com/theSamyak/FCC-Blog-CodeArchive/tree/main/Client-Side%20Form%20Handling%20with%20JavaScript">GitHub</a>.</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents</strong></h2>
<ol>
<li><a class="post-section-overview" href="#heading-understanding-html-forms">Understanding HTML Forms</a><br>– <a class="post-section-overview" href="#heading-introduction-to-html-form-elements">Introduction to HTML form elements</a><br>– <a class="post-section-overview" href="#heading-javascript-and-form-handling">JavaScript and Form Handling</a><br>– <a class="post-section-overview" href="#accessing-form-fields">Accessing Form Fields</a><br>– <a class="post-section-overview" href="#heading-lets-see-an-example-registration-form">Example: Registration Form</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-radio-buttons">How to Create Radio Buttons</a><br>– <a class="post-section-overview" href="#javascript-to-handle-radio-button-selection">JavaScript to Handle Radio Button Selection</a><br>– <a class="post-section-overview" href="#heading-radio-button-change-event">Radio Button Change Event</a></li>
<li><a class="post-section-overview" href="#heading-checkboxes">Checkboxes</a><br>– <a class="post-section-overview" href="#heading-how-to-check-if-a-checkbox-is-checked">How to Check if a Checkbox is Checked</a><br>– <a class="post-section-overview" href="#heading-how-to-get-checkbox-values">How to Get Checkbox Values</a><br>– <a class="post-section-overview" href="#heading-how-to-handle-multiple-checkboxes">How to Handle Multiple Checkboxes</a><br>– <a class="post-section-overview" href="#heading-how-to-check-uncheck-all-checkboxes">How to Check / Uncheck All Checkboxes</a><br>– <a class="post-section-overview" href="#heading-how-to-dynamically-generate-checkboxes">How to Dynamically Generate CheckBoxes</a></li>
<li><a class="post-section-overview" href="#select-element">Select Element</a><br>– <a class="post-section-overview" href="#how-to-interact-with-a-select-element">How to Interact with a Select Element</a><br>– <a class="post-section-overview" href="#heading-how-to-access-options-with-javascript">How to Access Options with JavaScript</a><br>– <a class="post-section-overview" href="#how-to-handle-multiple-selections">How to Handle Multiple Selections</a><br>– <a class="post-section-overview" href="#lets-see-an-example-task-manager-adding-and-removing-tasks">Example: Task Manager</a></li>
<li><a class="post-section-overview" href="#heading-difference-between-change-and-input-event">Difference Between Change and Input Event</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<p>Before we start, here's something to note:</p>
<p>This is a follow up blog on this <a target="_blank" href="https://www.freecodecamp.org/news/javascript-in-the-browser-dom-and-events/">DOM and Events Handbook</a> and not cover server-side communication/server-side form handling in this blog as it involves advanced topics such as AJAX (Asynchronous JavaScript and XML), Promises, error handling, and handling asynchronous operations in JavaScript.</p>
<p>In this tutorial, we'll instead focuses on how to work with various form elements including radio buttons, checkboxes, and select elements, as well as dynamically generating and interacting with them using JavaScript. </p>
<p>Delving into server-side communication would extend beyond the scope of this article, which aims to provide a comprehensive understanding of DOM manipulation and event handling within the context of form elements.</p>
<h2 id="heading-understanding-html-forms">Understanding HTML Forms</h2>
<p>HTML forms are fundamental elements used for collecting and submitting user data on the web. They enable interaction between users and websites by allowing users to input information, make selections, and submit data to servers for processing.</p>
<h4 id="heading-introduction-to-html-form-elements">Introduction to HTML Form Elements</h4>
<p>HTML forms are created using the <code>&lt;form&gt;</code> element, which acts as a container for various input elements. Common form elements include text fields, checkboxes, radio buttons, dropdown menus, and buttons.</p>
<p>To reference a form in JS, you can use DOM methods like <code>getElementById()</code> or <code>document.forms</code>. <code>document.forms</code> returns a collection of forms, and you can access a specific form using an index, name, or id.    </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'signup'</span>);
<span class="hljs-keyword">const</span> firstForm = <span class="hljs-built_in">document</span>.forms[<span class="hljs-number">0</span>]; <span class="hljs-comment">// accessing first form</span>
<span class="hljs-keyword">const</span> formByName = <span class="hljs-built_in">document</span>.forms[<span class="hljs-string">'formName'</span>]; <span class="hljs-comment">// accessing form by name</span>
<span class="hljs-keyword">const</span> formById = <span class="hljs-built_in">document</span>.forms[<span class="hljs-string">'formId'</span>]; <span class="hljs-comment">// accessing form by id</span>
</code></pre>
<p>Let's see a basic example of an HTML form:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"username"</span>&gt;</span>Username:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"password"</span>&gt;</span>Password:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Submit"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>In this example, we have a form with two input fields for username and password, along with a submit button.</p>
<h3 id="heading-form-structure-and-attributes">Form Structure and Attributes</h3>
<p>HTML forms can have various attributes that control their behavior and appearance. Some common attributes include:</p>
<ul>
<li><strong>action:</strong> Specifies the URL where the form data should be submitted.</li>
<li><strong>method:</strong> Specifies the HTTP method used to send form data (<code>post</code> or <code>get</code>).</li>
<li><strong>target</strong>: Specifies where to display the response after form submission (for example, <code>_self</code>, <code>_blank</code>, <code>_parent</code>, <code>_top</code>).</li>
<li><strong>name</strong>: Assigns a name to the form for identification purposes.</li>
</ul>
<p>Here's an example of a form with action, method, and target attributes:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"/submit-form"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"POST"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"myForm"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span>
  <span class="hljs-comment">&lt;!-- Form elements go here --&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<h3 id="heading-javascript-and-form-handling">JavaScript and Form Handling</h3>
<p>JavaScript uses the <code>HTMLFormElement</code> object to represent a form. This object has properties corresponding to the HTML attributes <code>action</code> and <code>method</code>.</p>
<p>Methods like <code>submit()</code> and <code>reset()</code> are used for submitting and resetting forms.</p>
<pre><code class="lang-html">const form = document.getElementById('signup');
form.action; // returns the action attribute
form.method; // returns the method attribute
form.submit(); // submits the form
</code></pre>
<p>JavaScript provides Event Handlers to add interactivity to HTML forms. By leveraging these events, you can execute custom scripts in response to user actions within the form:</p>
<p><strong>Submit Event</strong>: A form typically has a submit button, which when clicked, sends the form data to the server. This is achieved using an <code>&lt;input&gt;</code> or <code>&lt;button&gt;</code> element with <code>type="submit"</code>.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Sign Up"</span>&gt;</span>
// or
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Sign Up<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>To attach an event listener to the submit event, you use the <code>addEventListener()</code> method. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'signup'</span>);
form.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    <span class="hljs-comment">// Custom validation and submission logic here</span>
});
</code></pre>
<p>In many cases, you may want to intercept the default form submission behavior and execute custom logic before allowing the form to be submitted to the server. You can use <code>preventDefault()</code> for this. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'signup'</span>);
form.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    event.preventDefault(); <span class="hljs-comment">// Prevents the default form submission</span>
    <span class="hljs-comment">// Custom validation and submission logic here</span>
});
</code></pre>
<p>Without <code>event.preventDefault()</code>, any custom validation and submission logic would still execute within the event listener, but the default form submission behavior would not be prevented.</p>
<p><strong>Reset Event</strong>: The <code>reset</code> event is triggered when the form is reset using a reset button or programmatically. We use <code>reset()</code> method to clear all form fields and reset them to their default values.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'form'</span>).addEventListener(<span class="hljs-string">'reset'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
    <span class="hljs-comment">// Custom form reset logic here</span>
});
</code></pre>
<h3 id="heading-how-to-access-form-fields">How to Access Form Fields</h3>
<p>You can access form fields using DOM methods like <code>getElementsByName()</code>, <code>getElementById()</code>, <code>querySelector()</code>, and so on</p>
<p>The <code>form.elements</code> property stores a collection of form elements. You can access these Elements by index, id, or name. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'signup'</span>);
<span class="hljs-keyword">const</span> nameField = form.elements[<span class="hljs-string">'name'</span>]; <span class="hljs-comment">// accessing element by name</span>
<span class="hljs-keyword">const</span> emailField = form.elements[<span class="hljs-string">'email'</span>]; <span class="hljs-comment">// accessing element by name</span>
<span class="hljs-keyword">const</span> firstElement = form.elements[<span class="hljs-number">0</span>]; <span class="hljs-comment">// accessing first element by index no.</span>
</code></pre>
<p>Once you've accessed a form field, you can use the <code>value</code> property to access its value. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> nameValue = nameField.value;
<span class="hljs-keyword">const</span> emailValue = emailFieldByName.value;
</code></pre>
<h3 id="heading-form-validation">Form Validation</h3>
<p>Form validation is an essential aspect of web development that ensures the data submitted by users is accurate and meets specified criteria before being processed by the server. Common validations include checking for empty fields, valid email formats, and so on.</p>
<h4 id="heading-html-form-validation">HTML Form Validation</h4>
<p>HTML5 provides built-in form validation through various attributes:</p>
<ul>
<li><strong>required</strong>: Specifies that a field must be filled out.</li>
<li><strong>pattern</strong>: Specifies a regular expression pattern that the input value must match.</li>
<li><strong>min</strong> and <strong>max</strong>: Specify the minimum and maximum values for an input field.</li>
<li><strong>maxlength</strong> and <strong>minlength</strong>: Specify the maximum and minimum length of the input</li>
<li><strong>type</strong>: Specifies the type of input expected (for example, email, number, date).</li>
</ul>
<p>Here's an example of HTML form validation using these attributes:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"username"</span>&gt;</span>Username:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">required</span> <span class="hljs-attr">minlength</span>=<span class="hljs-string">"3"</span> <span class="hljs-attr">maxlength</span>=<span class="hljs-string">"15"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"email"</span>&gt;</span>Email:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">required</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"age"</span>&gt;</span>Age:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"age"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"age"</span> <span class="hljs-attr">min</span>=<span class="hljs-string">"18"</span> <span class="hljs-attr">max</span>=<span class="hljs-string">"99"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Submit"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<h4 id="heading-javascript-form-validation">JavaScript Form Validation</h4>
<p>JavaScript allows developers to perform more sophisticated validation logic beyond what HTML attributes offer. Event listeners can be attached to form elements to handle validation dynamically. </p>
<p>Here's a basic example of JavaScript form validation:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'form'</span>);

form.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
    event.preventDefault(); <span class="hljs-comment">// Prevent form submission</span>

    <span class="hljs-comment">// Perform custom validation logic</span>
    <span class="hljs-keyword">const</span> email = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'email'</span>).value;
    <span class="hljs-keyword">const</span> password = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'password'</span>).value;

    <span class="hljs-keyword">if</span> (!emailIsValid(email)) {
        alert(<span class="hljs-string">'Please enter a valid email address.'</span>);
        <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-keyword">if</span> (password.length &lt; <span class="hljs-number">6</span>) {
        alert(<span class="hljs-string">'Password must be at least 6 characters long.'</span>);
        <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-comment">// If validation passes, submit the form</span>
    form.submit();
});

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">emailIsValid</span>(<span class="hljs-params">email</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-regexp">/^[^\s@]+@[^\s@]+\.[^\s@]+$/</span>.test(email);
}
</code></pre>
<p>In this example, the JavaScript function <code>emailIsValid()</code> uses a regular expression to validate the email format. The <code>submit</code> event listener prevents the form from being submitted if the validation fails, and custom error messages are displayed to the user.</p>
<h3 id="heading-lets-see-an-example-registration-form">Let's See an Example: Registration Form</h3>
<p>Now, let's combine all the concepts we've covered into a complete example of a Registration form with client-side validation using JavaScript:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>User Registration<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"registrationForm"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"username"</span>&gt;</span>Username:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"email"</span>&gt;</span>Email:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"password"</span>&gt;</span>Password:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Register"</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"errorMessages"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><strong>HTML Structure</strong>: We have a simple registration form with fields for username, email, password, and a submit button. There's also a container div (<code>errorMessages</code>) to display validation error messages.</p>
<p>Now let's write JavaScript code to handle form submission and perform client-side validation:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> registrationForm = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"registrationForm"</span>);
<span class="hljs-keyword">const</span> errorMessages = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"errorMessages"</span>);

registrationForm.addEventListener(<span class="hljs-string">"submit"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{
  event.preventDefault();

  <span class="hljs-keyword">const</span> { username, email, password } = registrationForm.elements;

  errorMessages.innerHTML = <span class="hljs-string">""</span>;

  <span class="hljs-keyword">if</span> (!username.value.trim()) {
    displayError(<span class="hljs-string">"Username is required."</span>);
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-keyword">if</span> (!email.value.trim() || !isValidEmail(email.value)) {
    displayError(<span class="hljs-string">"Please enter a valid email address."</span>);
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-keyword">if</span> (!password.value.trim() || !isStrongPassword(password.value)) {
    displayError(
      <span class="hljs-string">"Password must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, one digit, and one special character."</span>
    );
    <span class="hljs-keyword">return</span>;
  }

  alert(<span class="hljs-string">"Registration successful!"</span>);
  registrationForm.reset();
});

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayError</span>(<span class="hljs-params">message</span>) </span>{
  errorMessages.innerHTML += <span class="hljs-string">`&lt;div class="error"&gt;<span class="hljs-subst">${message}</span>&lt;/div&gt;`</span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isValidEmail</span>(<span class="hljs-params">email</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-regexp">/^[^\s@]+@[^\s@]+\.[^\s@]+$/</span>.test(email);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isStrongPassword</span>(<span class="hljs-params">password</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-regexp">/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&amp;*]).{8,}$/</span>.test(password);
}
</code></pre>
<p><strong>JavaScript Handling</strong>: We select the form and the error message container using <code>getElementById</code>. We attach an event listener to the form's submit event. When the form is submitted, we prevent its default behavior using <code>event.preventDefault()</code> to handle form submission manually.</p>
<p><strong>Form Validation</strong>: We retrieve the values of username, email, and password.</p>
<p>We perform basic validation: Username must not be empty, Email must be in a valid format, Password must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, one digit, and one special character.</p>
<p><strong>Error Handling</strong>: If any validation fails, we display the corresponding error message. Error messages are displayed in the <code>errorMessages</code> div.</p>
<p><strong>Form Reset</strong>: Upon successful registration (in this case, a simple alert), we reset the form using <code>registrationForm.reset()</code></p>
<p>Currently, the code uses an <code>alert</code> to indicate successful registration. In a real scenario, you might want to implement an AJAX call to submit the data to a server for processing and handle the response accordingly But that's not what we're going to discuss, as mentioned at the start of this tutorial.</p>
<p>Overall this example covers form creation, form handling with JavaScript, form validation using regular expressions, and dynamic custom error message display, demonstrating a basic user registration form with client-side validation.</p>
<h2 id="heading-radio-buttons">Radio Buttons</h2>
<p>Radio buttons are a common form element used to select one option from a set of options. In JavaScript, you can manipulate radio buttons to retrieve user selections and perform actions based on those selections.</p>
<h3 id="heading-how-to-create-radio-buttons">How to Create Radio Buttons</h3>
<p>You can use radio buttons you want users to select only one option from a set of choices. In HTML, you can create radio buttons using the <code>&lt;input&gt;</code> element with the <code>type</code> attribute set to "radio". A group of radio buttons with the same <code>name</code> attribute forms a radio group. </p>
<p>Here's an example:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"languageForm"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Select your favorite programming language:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"radio"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"JavaScript"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"js"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"js"</span>&gt;</span>JavaScript<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"radio"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Python"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"python"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"python"</span>&gt;</span>Python<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"radio"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Java"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"java"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"java"</span>&gt;</span>Java<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-comment">&lt;!-- More language options can be added here --&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>You use the <code>id</code> and <code>for</code> attributes for accessibility, linking the label to the corresponding radio button.</p>
<h3 id="heading-how-to-retreive-the-selected-radio-button-value">How to Retreive the Selected Radio Button Value</h3>
<p>Now, let's discuss how to retrieve the value of the selected radio button using JavaScript.</p>
<pre><code class="lang-html">    <span class="hljs-comment">&lt;!-- HTML --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn"</span>&gt;</span>Show Selected Language<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"output"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#btn"</span>);
      <span class="hljs-keyword">const</span> radioButtons = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'input[name="language"]'</span>);
      <span class="hljs-keyword">const</span> output = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"output"</span>);

      btn.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">let</span> selectedLanguage;
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> radioButton <span class="hljs-keyword">of</span> radioButtons) {
          <span class="hljs-keyword">if</span> (radioButton.checked) {
            selectedLanguage = radioButton.value;
            <span class="hljs-keyword">break</span>;
          }
        }
        <span class="hljs-comment">// Displaying the output:</span>
        output.innerText = selectedLanguage
          ? <span class="hljs-string">`You selected <span class="hljs-subst">${selectedLanguage}</span>`</span>
          : <span class="hljs-string">`You haven't selected any language`</span>;
      });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>Here's how this the code works: the JavaScript code initializes by selecting the button, radio buttons, and output elements from the HTML document. We add a click event listener to the button element. When the button is clicked, the function inside the event listener is executed.</p>
<p>Inside the click event listener, we iterate over all radio buttons in the <code>radioButtons</code> collection. We check if a radio button is checked using its <code>checked</code> property. If a radio button is checked, we assign its value to the <code>selectedLanguage</code> variable and exit the loop using <code>break</code>.</p>
<p>We update the content of the output element (<code>&lt;p&gt;</code> tag with id <code>output</code>) based on whether a language is selected. If a language is selected (<code>selectedLanguage</code> is truthy), we display a message indicating the selected language. Otherwise, we prompt the user to select a language.</p>
<h3 id="heading-radio-button-change-event">Radio Button Change Event</h3>
<p>When a radio button is checked or unchecked, it fires a <code>change</code> event. You can listen to this event using <code>addEventListener()</code>. Inside the event handler, you can access the checked state and value of the radio button using <code>this.checked</code> and <code>this.value</code>.</p>
<pre><code class="lang-javascript">radioButton.addEventListener(<span class="hljs-string">'change'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.checked) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.value);
  }
});
</code></pre>
<h3 id="heading-how-to-dynamically-generate-radio-buttons">How to Dynamically Generate Radio Buttons</h3>
<p>Now, let's explore how to dynamically generate radio buttons using JavaScript. This is useful when you want to create radio button options dynamically based on certain criteria or data.</p>
<p>Suppose we have an array of languages, and we want to dynamically generate radio buttons for each language option:</p>
<pre><code class="lang-javascript">&lt;!DOCTYPE html&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"languages"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> languageOptions = [<span class="hljs-string">"Python"</span>, <span class="hljs-string">"Javascript"</span>, <span class="hljs-string">"C++"</span>, <span class="hljs-string">"Java"</span>];

      <span class="hljs-comment">// Generate the radio buttons</span>
      <span class="hljs-keyword">const</span> languages = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#languages"</span>);
      languages.innerHTML = languageOptions.map(<span class="hljs-function">(<span class="hljs-params">language</span>) =&gt;</span> <span class="hljs-string">`
          &lt;div&gt;
              &lt;input type="radio" name="language" value="<span class="hljs-subst">${language}</span>" id="<span class="hljs-subst">${language}</span>"&gt;
              &lt;label for="<span class="hljs-subst">${language}</span>"&gt;<span class="hljs-subst">${language}</span>&lt;/label&gt;
          &lt;/div&gt;`</span>).join(<span class="hljs-string">' '</span>);
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></span>
</code></pre>
<p>It dynamically generates radio buttons based on the <code>languageOptions</code> array and inserts them into the container element (<code>&lt;div id="languages"&gt;&lt;/div&gt;</code>). Each radio button has a unique ID and value corresponding to the language name, and the labels are associated with their respective radio buttons using the <code>for</code> attribute.</p>
<p>After dynamically generating the radio buttons, Now let's add <code>change</code> event listeners to them to handle changes in selection.</p>
<pre><code class="lang-javascript">    &lt;!-- HTML --&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"languages"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"languageOutput"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span> <span class="hljs-comment">// we create this one to fetch our selected language output</span>

    &lt;!-- Generate the radio buttons --&gt;

<span class="hljs-comment">// Attaching Change Event Listeners</span>
<span class="hljs-keyword">const</span> radioButtons = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'input[name="language"]'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> radioButton <span class="hljs-keyword">of</span> radioButtons) {
    radioButton.addEventListener(<span class="hljs-string">'change'</span>, showSelectedlanguage);
}        

<span class="hljs-comment">// Handling the Change Event</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showSelectedlanguage</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.checked) {
        <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#languageOutput'</span>).innerText = <span class="hljs-string">`You selected <span class="hljs-subst">${<span class="hljs-built_in">this</span>.value}</span>`</span>;
    }
}
</code></pre>
<p>Here's what's happening:</p>
<ul>
<li>We select all radio buttons with the <code>name</code> attribute set to <code>"language"</code>.</li>
<li>We use a <code>for...of</code> loop to iterate over each radio button and add a <code>change</code> event listener to each radio button. This listener listens for changes in the state of the radio buttons, i.e., when a radio button is selected or deselected.</li>
<li>We define a function named <code>showSelectedLanguage</code> to handle the change event triggered by selecting a radio button. </li>
<li>Inside the <code>showSelectedLanguage</code> function, we first check if the current radio button (<code>this</code>) is checked using the <code>checked</code> property. If the radio button is checked, we update the text content of an element with the id <code>languageOutput</code> using <code>document.querySelector('#languageOutput')</code>. This element serves as a placeholder to display the selected language.</li>
</ul>
<p>This setup ensures that dynamically generated radio buttons have <code>change</code> event listeners attached to them, allowing for dynamic handling of user selections.</p>
<h2 id="heading-checkboxes">Checkboxes</h2>
<h3 id="heading-how-to-create-an-html-checkbox">How to Create an HTML Checkbox</h3>
<p>Let's first create a checkbox using the <code>&lt;input&gt;</code> element and type attribute set to "checkbox". let's associate it with label for better accessibility.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"agree"</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"agree"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"agree"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"yes"</span>&gt;</span> I agree to the terms
<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
</code></pre>
<h3 id="heading-how-to-check-if-a-checkbox-is-checked">How to Check if a Checkbox is Checked</h3>
<p>A checkbox in HTML can exist in two states: checked and unchecked. And we can determine which is active using <code>checked</code> property. If it's <code>true</code>, the checkbox is checked – otherwise, it's unchecked. Example:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"agree"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"agree"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"agree"</span>&gt;</span> I agree to the terms
    <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
        <span class="hljs-keyword">const</span> checkbox = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'agree'</span>);
        <span class="hljs-built_in">console</span>.log(checkbox.checked);
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h3 id="heading-how-to-get-checkbox-values">How to Get Checkbox Values</h3>
<p>In HTML forms, when a checkbox is checked and the form is submitted, the browser includes the checkbox in the form data with its <code>name</code> attribute as the key and the <code>value</code> attribute (if specified) as the value. But if the checkbox is unchecked, it's not included in the form data at all.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"agree"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"agree"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"agree"</span>&gt;</span> I agree to the terms
<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn"</span>&gt;</span>Show Value<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-keyword">const</span> checkbox = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#agree'</span>);
    <span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#btn'</span>);
    btn.onclick = <span class="hljs-function">() =&gt;</span> {
       alert(checkbox.value);
    };
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>So basically the point is: When a checkbox is checked and included in form submissions, the browser defaults to sending <code>'on'</code> as the value if no <code>value</code> attribute is explicitly defined for the checkbox input element. To accurately handle the checked state of a checkbox using JavaScript, use the <code>checked</code> property instead of relying solely on the <code>value</code> attribute.</p>
<h3 id="heading-how-to-handle-multiple-checkboxes">How to Handle Multiple Checkboxes</h3>
<p>Sometimes, you may need to work with multiple checkboxes with the same name and you want to retrieve the values of the selected checkboxes. Here's an example:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Select your preferred languages:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"l1"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"C++"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"l1"</span> /&gt;</span>C++
    <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"l2"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Python"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"l2"</span> /&gt;</span>Python
    <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"l3"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Java"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"l3"</span> /&gt;</span>Java
    <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn"</span>&gt;</span>Get Selected Languages<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#btn"</span>);
      btn.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">const</span> checkboxes = <span class="hljs-built_in">document</span>.querySelectorAll(
          <span class="hljs-string">'input[name="language"]:checked'</span>
        );
        <span class="hljs-keyword">const</span> selectedLanguages = <span class="hljs-built_in">Array</span>.from(checkboxes).map(
          <span class="hljs-function">(<span class="hljs-params">checkbox</span>) =&gt;</span> checkbox.value
        );
        alert(<span class="hljs-string">"Selected Languages: "</span> + selectedLanguages.join(<span class="hljs-string">", "</span>));
      });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>In this example, we have checkboxes for selecting preferred programming languages.</p>
<ul>
<li>When the button is clicked, it triggers an event listener. Inside the event listener, we select all checkboxes with the name attribute "language" that are checked.</li>
<li>We then convert the NodeList returned by <code>querySelectorAll()</code> into an array using <code>Array.from()</code>.</li>
<li>Finally, we map over the array to retrieve the values of selected checkboxes and display them using <code>alert()</code>.</li>
</ul>
<h3 id="heading-how-to-check-uncheck-all-checkboxes">How to Check / Uncheck All Checkboxes</h3>
<p>Now, let's create a functionality to check or uncheck all checkboxes at once:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn"</span>&gt;</span>Check / Uncheck All<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Select your preferred languages:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"l1"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"C++"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"l1"</span> /&gt;</span>C++
    <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"l2"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Python"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"l2"</span> /&gt;</span>Python
    <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"l3"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Java"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"l3"</span> /&gt;</span>Java
    <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Javascript code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// function to check or uncheck all checkboxes</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">check</span>(<span class="hljs-params">checked = true</span>) </span>{
  <span class="hljs-keyword">const</span> checkboxes = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'input[name="language"]'</span>);

  <span class="hljs-comment">// Iterate through each checkbox</span>
  checkboxes.forEach(<span class="hljs-function">(<span class="hljs-params">checkbox</span>) =&gt;</span> {
    <span class="hljs-comment">// Set the checked property of each checkbox to the value of the 'checked' parameter</span>
    checkbox.checked = checked;
  });
}

<span class="hljs-comment">// function to check all checkboxes and change button behavior to uncheck all</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkAll</span>(<span class="hljs-params"></span>) </span>{
  check();
  <span class="hljs-built_in">this</span>.onclick = uncheckAll;
}

<span class="hljs-comment">// function to uncheck all checkboxes and change button behavior to check all</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">uncheckAll</span>(<span class="hljs-params"></span>) </span>{
  check(<span class="hljs-literal">false</span>);
  <span class="hljs-built_in">this</span>.onclick = checkAll;
}

<span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#btn"</span>);

btn.onclick = checkAll;
</code></pre>
<p>In this example, we have a button labeled "Check / Uncheck All".</p>
<ul>
<li>When the button is first clicked, it's intended to check all the checkboxes. Therefore, the <code>checkAll</code> function is assigned to handle this action (<code>const btn = document.querySelector("#btn");</code>).</li>
<li>If the button is clicked again, it unchecks all checkboxes. We define functions <code>check()</code>, <code>checkAll()</code>, and <code>uncheckAll()</code> to handle the checking and unchecking of checkboxes.</li>
<li>We assign <code>checkAll()</code> to the button's <code>onclick</code> event initially, and then switch between <code>checkAll()</code> and <code>uncheckAll()</code> based on the current state of the checkboxes.</li>
</ul>
<p>Alternate approach could be:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkAll</span>(<span class="hljs-params">checked = true</span>) </span>{
  <span class="hljs-keyword">const</span> checkboxes = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'input[name="language"]'</span>);
  checkboxes.forEach(<span class="hljs-function">(<span class="hljs-params">checkbox</span>) =&gt;</span> {
    checkbox.checked = checked;
  });
}

<span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#btn"</span>);

btn.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// Find the first checkbox with the name attribute set to 'language'</span>
  <span class="hljs-keyword">const</span> firstCheckbox = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'input[name="language"]'</span>);
  <span class="hljs-comment">// Check if the first checkbox is checked</span>
  <span class="hljs-keyword">const</span> isChecked = firstCheckbox.checked;
  <span class="hljs-comment">// Call the checkAll function with the opposite state of the first checkbox</span>
  checkAll(!isChecked);
});
</code></pre>
<p>Here, we select the first checkbox with the name "language" to determine its current checked state. Then, we call <code>checkAll()</code> with the opposite state.</p>
<h3 id="heading-how-to-dynamically-generate-checkboxes">How to Dynamically Generate CheckBoxes</h3>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"languages"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> languageOptions = [<span class="hljs-string">"Python"</span>, <span class="hljs-string">"Javascript"</span>, <span class="hljs-string">"C++"</span>, <span class="hljs-string">"Java"</span>];

      <span class="hljs-comment">// Generate the checkboxes</span>
      <span class="hljs-keyword">const</span> html = languageOptions
        .map(
          <span class="hljs-function">(<span class="hljs-params">language</span>) =&gt;</span> <span class="hljs-string">`&lt;label for="language-<span class="hljs-subst">${language}</span>"&gt;
                &lt;input type="checkbox" name="language" id="language-<span class="hljs-subst">${language}</span>" value="<span class="hljs-subst">${language}</span>"&gt; <span class="hljs-subst">${language}</span>
            &lt;/label&gt;`</span>
        )
        .join(<span class="hljs-string">" "</span>);
      <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#languages"</span>).innerHTML = html;
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Here's how it works:</p>
<ul>
<li>We define an array <code>languageOptions</code> containing language names.</li>
<li>We use the <code>map()</code> method to iterate through the <code>languageOptions</code> array and generate an array of HTML strings for each language.</li>
<li>Each HTML string comprises a <code>label</code> element associated with an <code>input</code> checkbox. The <code>input</code> checkbox includes appropriate attributes such as <code>type</code>, <code>name</code>, <code>id</code>, and <code>value</code>, dynamically derived from the language name.</li>
<li>We join the array of HTML strings into a single string using <code>join(' ')</code>.</li>
<li>Finally, we set the <code>innerHTML</code> property of the root <code>&lt;div&gt;</code> element with the id <code>languages</code> to the generated HTML string, thereby rendering checkboxes for each programming language.</li>
</ul>
<h2 id="heading-select-element">Select Element:</h2>
<p>The <code>&lt;select&gt;</code> element in HTML provides a dropdown list of options for users to choose from. It allows for single or multiple selections. Example:</p>
<pre><code class="lang-javascript">&lt;select id=<span class="hljs-string">"cities"</span>&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"JAI"</span>&gt;</span>Jaipur<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"DEL"</span>&gt;</span>New Delhi<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"UDR"</span>&gt;</span>Udaipur<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"MUM"</span>&gt;</span>Mumbai<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span></span>
&lt;/select&gt;
</code></pre>
<p>By default, a <code>&lt;select&gt;</code> element allows for a single selection. To enable multiple selections, add the <code>multiple</code> attribute. </p>
<pre><code class="lang-javascript">&lt;select id=<span class="hljs-string">"cities"</span> multiple&gt;
</code></pre>
<p>Users can now select multiple fruits by holding down the Ctrl (or Cmd on Mac) key while clicking.</p>
<h3 id="heading-how-to-interact-with-a-select-element">How to Interact with a Select Element:</h3>
<p>To interact with a <code>&lt;select&gt;</code> element using JavaScript, we use the <code>HTMLSelectElement</code> type, which provides useful properties like <code>selectedIndex</code> and <code>value</code>. Example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">const</span> selectElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'cities'</span>);
<span class="hljs-built_in">console</span>.log(selectElement.selectedIndex); <span class="hljs-comment">// Returns the index of the selected option</span>
<span class="hljs-built_in">console</span>.log(selectElement.value); <span class="hljs-comment">// Returns the value of the selected option</span>
<span class="hljs-built_in">console</span>.log(selectElement.multiple); <span class="hljs-comment">// Returns true if multiple selections are allowed</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>JavaScript allows you to handle events on the <code>&lt;select&gt;</code> element, such as when a user selects an option. Example:</p>
<pre><code class="lang-javascript">&lt;button id=<span class="hljs-string">"btn"</span>&gt;Get Selected City&lt;/button&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#btn"</span>);
      <span class="hljs-keyword">const</span> selectElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"cities"</span>);
      btn.onclick = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
        event.preventDefault();
        <span class="hljs-keyword">const</span> selectedCity =
          selectElement.options[selectElement.selectedIndex].text;
        alert(<span class="hljs-string">`Selected city: <span class="hljs-subst">${selectedCity}</span>, 
        Index: <span class="hljs-subst">${selectElement.selectedIndex}</span>`</span>);
      };
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre>
<p><strong>Using the <code>value</code> property:</strong> The <code>value</code> property represents the value of the selected option. Let's understand it with example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"cities"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">""</span>&gt;</span>Jaipur<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"DEL"</span>&gt;</span>New Delhi<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"UDR"</span>&gt;</span>Udaipur<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">option</span>&gt;</span>Mumbai<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#btn"</span>);
<span class="hljs-keyword">const</span> selectElement = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#cities"</span>);

btn.onclick = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    event.preventDefault();
    alert(selectElement.value);
};
</code></pre>
<ul>
<li>If "Jaipur" is selected, this means we have an empty string since the value attribute is empty in our Html.</li>
<li>If an option lacks a value attribute, the select box's value property becomes the text of the selected option. Example: if "Mumbai" is selected, the value property is "Mumbai".</li>
<li>If multiple options are selected, the <code>value</code> property of the select box is derived from the first selected option based on the previous rules.</li>
</ul>
<h3 id="heading-how-to-access-options-with-javascript">How to Access Options with JavaScript</h3>
<p>The <code>HTMLOptionElement</code> type represents individual <code>&lt;option&gt;</code> elements within a <code>&lt;select&gt;</code> element in JavaScript. It provides properties like <code>index</code>, <code>selected</code>, <code>text</code>, and <code>value</code> to access information about each option. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> selectElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'cities'</span>);
<span class="hljs-keyword">const</span> secondOptionText = selectElement.options[<span class="hljs-number">1</span>].text; <span class="hljs-comment">// Accessing text of the second option</span>
<span class="hljs-keyword">const</span> secondOptionValue = selectElement.options[<span class="hljs-number">1</span>].value; <span class="hljs-comment">// Accessing value of the second option</span>
</code></pre>
<h3 id="heading-how-to-handle-multiple-selections">How to Handle Multiple Selections:</h3>
<p>When a <code>&lt;select&gt;</code> element allows multiple selections, you can iterate through its options to find which ones are selected and retrieve their text values. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> selectElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'cities'</span>);
<span class="hljs-keyword">const</span> selectedOptions = <span class="hljs-built_in">Array</span>.from(selectElement.options).filter(<span class="hljs-function"><span class="hljs-params">option</span> =&gt;</span> option.selected);
<span class="hljs-keyword">const</span> selectedValues = selectedOptions.map(<span class="hljs-function"><span class="hljs-params">option</span> =&gt;</span> option.text);
</code></pre>
<p>The output will be an array containing text of selected options. We can use <code>option.value</code> to get an array of values instead. Example:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"cities"</span> <span class="hljs-attr">multiple</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"JAI"</span>&gt;</span>Jaipur<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"DEL"</span>&gt;</span>New Delhi<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"UDR"</span>&gt;</span>Udaipur<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"MUM"</span>&gt;</span>Mumbai<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn"</span>&gt;</span>Get Selected Cities<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#btn"</span>);
      <span class="hljs-keyword">const</span> selectElement = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#cities"</span>);

      btn.onclick = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
        event.preventDefault();
        <span class="hljs-keyword">const</span> selectedOptions = <span class="hljs-built_in">Array</span>.from(selectElement.options)
          .filter(<span class="hljs-function">(<span class="hljs-params">option</span>) =&gt;</span> option.selected)
          .map(<span class="hljs-function">(<span class="hljs-params">option</span>) =&gt;</span> option.text);
        alert(<span class="hljs-string">"Selected City: "</span> + selectedOptions.join(<span class="hljs-string">", "</span>));
      };
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<ul>
<li>When the button is clicked, the script collects the selected options by filtering the options based on the <code>selected</code> property. It then maps over the selected options to retrieve their text content.</li>
<li>Finally, it displays the selected languages in an alert message.</li>
</ul>
<h3 id="heading-lets-see-an-example-task-manager-adding-and-removing-tasks">Let's See an Example: Task Manager (Adding and Removing Tasks)</h3>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
    <span class="hljs-selector-id">#container</span> {
      <span class="hljs-attribute">max-width</span>: <span class="hljs-number">540px</span>;
      <span class="hljs-attribute">margin</span>: <span class="hljs-number">50px</span> auto;
    }

    <span class="hljs-selector-tag">form</span> {
      <span class="hljs-attribute">display</span>: flex;
      <span class="hljs-attribute">flex-direction</span>: column;
    }
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"container"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"task"</span>&gt;</span>Task:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
          <span class="hljs-attr">id</span>=<span class="hljs-string">"task"</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter a task"</span>
          <span class="hljs-attr">autocomplete</span>=<span class="hljs-string">"off"</span>
        /&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btnAdd"</span>&gt;</span>Add Task<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"taskList"</span>&gt;</span>Task List:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"taskList"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"taskList"</span> <span class="hljs-attr">multiple</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btnRemove"</span>&gt;</span>Remove Selected Tasks<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>This HTML structure includes input fields for entering task descriptions, buttons for adding and removing tasks, and a <code>&lt;select&gt;</code> element to display the list of tasks. We added a little css for clarity. Let's see Javascript code now:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> btnAdd = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#btnAdd'</span>);
<span class="hljs-keyword">const</span> btnRemove = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#btnRemove'</span>);
<span class="hljs-keyword">const</span> taskList = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#taskList'</span>);
<span class="hljs-keyword">const</span> taskInput = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#task'</span>);

btnAdd.onclick = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    e.preventDefault();

    <span class="hljs-comment">// Validate the task input</span>
    <span class="hljs-keyword">if</span> (taskInput.value.trim() === <span class="hljs-string">''</span>) {
        alert(<span class="hljs-string">'Please enter a task description.'</span>);
        <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-comment">// Create a new task option</span>
    <span class="hljs-keyword">const</span> option = <span class="hljs-keyword">new</span> Option(taskInput.value, taskInput.value);
    taskList.add(option, <span class="hljs-literal">undefined</span>);

    <span class="hljs-comment">// Reset the task input</span>
    taskInput.value = <span class="hljs-string">''</span>;
    taskInput.focus();
};

btnRemove.onclick = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    e.preventDefault();

    <span class="hljs-comment">// Save the selected tasks</span>
    <span class="hljs-keyword">let</span> selectedTasks = [];

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; taskList.options.length; i++) {
        selectedTasks[i] = taskList.options[i].selected;
    }

    <span class="hljs-comment">// Remove selected tasks</span>
    <span class="hljs-keyword">let</span> index = taskList.options.length;
    <span class="hljs-keyword">while</span> (index--) {
        <span class="hljs-keyword">if</span> (selectedTasks[index]) {
            taskList.remove(index);
        }
    }
};
</code></pre>
<p>Explaination: we select the necessary elements from the HTML and attach event listeners to the "Add Task" and "Remove Selected Tasks" buttons. When the "Add Task" button is clicked, we create a new task option based on the input field value and add it to the <code>&lt;select&gt;</code> element. When the "Remove Selected Tasks" button is clicked, we remove the selected tasks from the <code>&lt;select&gt;</code> element.</p>
<h2 id="heading-difference-between-change-and-input-event">Difference Between Change and Input Event</h2>
<p>The input event in JavaScript is triggered whenever the value of an input, <code>&lt;select&gt;</code>, or <code>&lt;textarea&gt;</code> element changes. Unlike the change event, which waits for a value to be committed (for example, when an input loses focus), the input event fires continuously as the value changes. The input event basically provides a way to respond to user input in real-time. Example: </p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"userInput"</span>&gt;</span>Enter Your Name:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"userInput"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Your name"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Your name is: <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"displayName"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript">&lt;script&gt;
    <span class="hljs-keyword">const</span> userInput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'userInput'</span>);
    <span class="hljs-keyword">const</span> Name = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'displayName'</span>);

    userInput.addEventListener(<span class="hljs-string">'input'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        Name.textContent = userInput.value || <span class="hljs-string">'Guest!'</span>;
    });
&lt;/script&gt;
</code></pre>
<ul>
<li>This JavaScript code selects the input field with the ID "userInput" and the span element with the ID "displayName".</li>
<li>An event listener is attached to the input event of the userInput field.</li>
<li>When the input event is triggered (for example, when typing in the input field), the event handler updates the text content of the <code>displayName</code> span dynamically to reflect the entered name, or it displays "Anonymous" if the input field is empty.</li>
<li>Now, if you change 'input' to 'change' here <code>userInput.addEventListener('input', function()</code> like this: <code>userInput.addEventListener('change', function()</code>, the event listener will be triggered only when the input field loses focus after a value has been entered (as opposed to continuously while the value is being changed in real-time).</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>By understanding the fundamentals of HTML form elements, attributes, and events, you can create dynamic and user-friendly web forms that enhance the user experience. </p>
<p>JavaScript plays a crucial role in handling form submissions, validating user input, and providing real-time feedback to users.</p>
<p>Through practical examples and detailed explanations, in this guide you've learned about working with radio buttons, checkboxes, select elements, and handling multiple selections. </p>
<p>Keep exploring and experimenting with the concepts presented here to create robust and intuitive forms for your web applications.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use HTML Forms – HTML Form Basics ]]>
                </title>
                <description>
                    <![CDATA[ By Kelechukwu Isaac Awoke HTML forms are used to get information from users. They are widely used in webpages or apps for surveys or registration processes.  HTML form basics include the common HTML elements, tags, attributes, concepts, or best pract... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-html-forms/</link>
                <guid isPermaLink="false">66d45f63264384a65d5a954a</guid>
                
                    <category>
                        <![CDATA[ Form validations ]]>
                    </category>
                
                    <category>
                        <![CDATA[ forms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 06 Mar 2024 10:37:42 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/glenn-carstens-peters-RLw-UC03Gwc-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Kelechukwu Isaac Awoke</p>
<p>HTML forms are used to get information from users. They are widely used in webpages or apps for surveys or registration processes. </p>
<p>HTML form basics include the common HTML elements, tags, attributes, concepts, or best practices required for you to create good HTML forms. The collected data is sent to a server for processing.</p>
<ul>
<li><a class="post-section-overview" href="#heading-basic-structure-of-html-form">Basic Structure of HTML Form</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-html-form-elements">How to Use HTML Form Elements</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-html-element">How to Use the HTML  Element</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-html-element">How to Use the HTML  Element</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-html">How to Use the HTML </a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-html-element">How to Use the HTML  Element</a></li>
<li><a class="post-section-overview" href="#heading-form-validation">Form Validation</a></li>
<li><a class="post-section-overview" href="#heading-importance-of-form-validation">Importance of Form Validation</a></li>
<li><a class="post-section-overview" href="#heading-types-of-form-validation">Types of Form Validation</a></li>
<li><a class="post-section-overview" href="#heading-common-validation-techniques">Common Validation Techniques</a></li>
<li><a class="post-section-overview" href="#heading-form-submission-and-methods">Form Submission and Methods</a></li>
<li><a class="post-section-overview" href="#heading-how-to-style-html-forms">How to Style HTML Forms</a></li>
<li><a class="post-section-overview" href="#heading-best-practices-and-accessibility">Best Practices and Accessibility</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-basic-structure-of-html-form">Basic Structure of HTML Form</h2>
<p>You can use the <code>&lt;form&gt;</code> element to create an HTML form</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"submit_form"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">" post"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"name"</span>&gt;</span>Name:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">" name"</span> <span class="hljs-attr">required</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"email"</span>&gt;</span>Email:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">required</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p> The HTML <code>&lt;form&gt;</code> element is a container for several HTML form elements. The <code>&lt;form&gt;</code> element can contain the following:</p>
<ul>
<li><code>&lt;input&gt;</code></li>
<li><code>&lt;label&gt;</code></li>
<li><code>&lt;select&gt;</code></li>
<li><code>&lt;textarea&gt;</code></li>
<li><code>&lt;button&gt;</code></li>
<li><code>&lt;fieldset&gt;</code></li>
<li><code>&lt;legend&gt;</code></li>
<li><code>&lt;datalist&gt;</code></li>
<li><code>&lt;output&gt;</code></li>
<li><code>&lt;option&gt;</code></li>
<li><code>&lt;optgroup&gt;</code></li>
</ul>
<h2 id="heading-how-to-use-html-form-elements">How to Use HTML Form Elements</h2>
<p>In this section, you'll learn how to use some of the HTML form elements.</p>
<h3 id="heading-how-to-use-the-html-element">How to Use the HTML  Element</h3>
<p>The <code>&lt;input&gt;</code> element is the most commonly used form element. The type of information an <code>&lt;input&gt;</code> element can hold depends on the <code>&lt;type&gt;</code> attribute. </p>
<p>The <code>&lt;input&gt;</code>  element can only accept a particular type of data assigned to it using the <code>&lt;type&gt;</code>  attribute.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">""</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
        <span class="hljs-attr">id</span>=<span class="hljs-string">"name"</span>
        <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span>
        <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter your username"</span>
        <span class="hljs-attr">required</span>
      /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span>
        <span class="hljs-attr">id</span>=<span class="hljs-string">"security"</span>
        <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span>
        <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter your password"</span>
        <span class="hljs-attr">required</span>
      /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter your email"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"subscribe"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"yes"</span> /&gt;</span> Subscribe to the
      newsletter <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"radio"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"gender"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"male"</span> /&gt;</span> Male
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"radio"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"gender"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"female"</span> /&gt;</span> Female
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"submit"</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p> The following are the different  <code>&lt;type&gt;</code> attributes that can be assigned to an <code>&lt;input&gt;</code> element:</p>
<ul>
<li><code>&lt;input type="text"&gt;</code>: Allows the user to type in text.</li>
<li><code>&lt;input type="email"&gt;</code>: The user input must follow an email format.</li>
<li><code>&lt;input type="password"&gt;</code> : Accepts password from the user. The passwords are masked, usually displayed as asterisks (*) or dots, to protect the privacy of the input.</li>
<li><code>&lt;input type="checkbox"&gt;</code>: The user can select none or many of the displayed checkboxes. Checkboxes can be checked or unchecked.</li>
<li><code>&lt;input type="radio"&gt;</code>: Allows the user to select only one from the multiple-choice radio buttons.</li>
<li><code>&lt;input type="submit"&gt;</code>: Enables the user to submit the form.</li>
</ul>
<p>The following are other possible attributes found in the input element:</p>
<ul>
<li><code>&lt;input name=" "&gt;</code> : Assigns the input field a name. The assigned name identifies the input data when the form is submitted.</li>
<li><code>&lt;input id=" "&gt;</code>: The identifier creates a unique id for the input field. It is usually associated with CSS for styling and JavaScript for other manipulations.</li>
<li><code>&lt;input value=" "&gt;</code>: Used to set the initial value for the input field. The default initial value gives the user an idea of the information required.</li>
<li><code>&lt;input placeholder=" "&gt;</code>: A faint pseudo value set to the input field that disappears once the user starts typing. Gives a hint on what data to enter, similar to the value attribute.</li>
<li><code>&lt;input required&gt;</code>: Requires that the input field must be filled out before submission. Gives an error message when not filled out.</li>
<li><code>&lt;input disabled&gt;</code>: As the name implies, this prevents the user from interacting with the input field. Disables the input field from accepting input. With this attribute, the input field becomes unclickable.</li>
<li><code>&lt;input readonly&gt;</code>: The user can only read the initially set value but can't change it. Unlike the disabled attribute, the input field is clickable but can't be modified.</li>
</ul>
<p>Note that the <code>&lt;input&gt;</code> element doesn't contain a <code>for</code> attribute.</p>
<h3 id="heading-how-to-use-the-html-element-1">How to Use the HTML  Element</h3>
<p>The label element associates text with a form input, checkbox, or radio button.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">" "</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"user"</span>&gt;</span>Username:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>The label element describes the information required in the text field.</p>
<p>The label element is important for accessibility, this makes it easier for screen-reader users to navigate the form. The assistive technologies read the label loud to users.</p>
<p>Clicking on the label focuses the corresponding input field when the <code>for</code> attribute of the label element corresponds with the id attribute of the input element, making it more convenient for users to interact with the form.</p>
<p>Label improves the overall usage of the form, providing context and guidance.</p>
<p>The following are the commonly used attributes for the <code>label</code> element:</p>
<ul>
<li><code>&lt;label for=" "&gt;&lt;/label&gt;</code>: Associates the label with the corresponding form element, usually an input element. The value of the <code>for</code> attribute is always the same as the id value of the associated form element, usually the input element.</li>
<li>id attribute <code>&lt;label id=" "&gt;&lt;/label&gt;</code>: Gives the label a unique identifier. The value is set to the same value with the <code>for</code> attribute of the corresponding form element, usually an input element. Used for selecting the label for styling in CSS or other manipulations in JavaScript.</li>
</ul>
<h3 id="heading-how-to-use-the-html">How to Use the HTML </h3>
<p>A multi-line text input field, allows users to write longer text or paragraphs. The <code>rows</code> and <code>cols</code> attributes control the initial size of the textarea box. </p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">""</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"testimony"</span>&gt;</span>Testimony:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">textarea</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"testimony"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"testimony"</span> <span class="hljs-attr">cols</span>=<span class="hljs-string">"30"</span> <span class="hljs-attr">rows</span>=<span class="hljs-string">"10"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">textarea</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>The <code>rows</code> attribute controls the height (vertical size) of the textarea box, determining the number of visible lines while the <code>cols</code> attribute controls the width (horizontal size), specifying the number of visible characters per line. </p>
<p>Note, that the <code>textarea</code> box can <em>wrap</em> to fit the entered text within its defined width.</p>
<p>Unlike the single-line input field, the <code>textarea</code> element does not have a <code>maxlength</code> attribute or <code>value</code> attribute. The content is placed within the opening and closing tags. </p>
<p>For accessibility, it's a good practice to associate label or context with the <code>textarea</code> element to assist users who use screen-readers or other assistive technologies.</p>
<h4 id="heading-how-to-use-the-html-element-2">How to Use the HTML  Element</h4>
<p>The <code>&lt;select&gt;</code> element creates a drop-down list, that allows users to select one or multiple options from the listed choices.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">""</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"numbers"</span>&gt;</span>Choose a favorite number:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"numbers"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"numbers"</span> <span class="hljs-attr">size</span>=<span class="hljs-string">"5"</span> <span class="hljs-attr">multiple</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">""</span> <span class="hljs-attr">disabled</span> <span class="hljs-attr">selected</span>&gt;</span>Select a number<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"one"</span>&gt;</span>1<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"two"</span>&gt;</span>2<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"three"</span>&gt;</span>3<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"four"</span>&gt;</span>4<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"five"</span>&gt;</span>5<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"six"</span>&gt;</span>6<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"seven"</span>&gt;</span>7<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"eight"</span>&gt;</span>8<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"nine"</span>&gt;</span>9<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"ten"</span>&gt;</span>10<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>The <code>&lt;option&gt;</code> element is contained within the <code>&lt;select&gt;</code> element. The <code>&lt;option&gt;</code> element holds the items to be selected. Each <code>&lt;option&gt;</code> represents one item in the drop-down list.</p>
<p>Each <code>&lt;option&gt;</code> element is expected to have a <code>&lt;value=" "&gt;</code> attribute, which holds the value to be submitted when the form containing the <code>&lt;select&gt;</code> element is submitted. If the <code>&lt;value=" "&gt;</code> attribute is omitted, the text content of the <code>&lt;option&gt;</code> element becomes the value to be submitted instead.</p>
<p>The <code>&lt;name=" "&gt;</code> attribute identifies the select control on the server side when the form is submitted. The <code>&lt;name=" "&gt;</code> is important for processing the form data on the server. </p>
<p>You can select one of the options as the default selection by including the <code>&lt;selected&gt;</code> attribute in the <code>&lt;option&gt;</code> element. If no option is selected, then the first option in the list will be selected by default.</p>
<p>The <code>&lt;size=" "&gt;</code> attribute sets the number of options you can see at once in the drop-down by setting the <code>&lt;size=" "&gt;</code> attribute on the <code>&lt;select&gt;</code>. Note that other options are seen as you scroll down. </p>
<p>Including the <code>&lt;disabled&gt;</code> attribute on the <code>&lt;select&gt;</code> element, disables the select option and prevents the users from selecting any option. The select option becomes unclickable. </p>
<p>Also, multiple options can be selected by including <code>&lt;multiple&gt;</code> attribute on the <code>&lt;select&gt;</code> element. You can hold the <code>Ctrl</code> (or Command on Mac) key to select multiple options.</p>
<p>Understanding the <code>&lt;select&gt;</code> element and using the necessary attributes can make your form convenient for users to select different options and for easy processing of the <code>&lt;select&gt;</code> element on the server side.</p>
<h2 id="heading-form-validation">Form Validation</h2>
<p>Simply put, this is the process of checking whether the data entered in the form is correct, complete, and meets the specified format.</p>
<h3 id="heading-importance-of-form-validation">Importance of Form Validation</h3>
<ul>
<li><strong>Data Accuracy:</strong>  Prevents submission of incorrect or incomplete data.</li>
<li><strong>Security:</strong> Checks the data to prevent incorrect or malicious data from being submitted, thereby reducing harmful attacks or data breaches. </li>
<li><strong>User Experience:</strong>  Makes filling out the forms less stressful by giving a quick error message if the user is entering the wrong data. Also, it can be used to suggest the expected format. </li>
<li><strong>Efficiency:</strong> Form validation before submission saves time and resources. Reduces unnecessary requests to the server, improving the overall performance of your application.</li>
</ul>
<h3 id="heading-types-of-form-validation">Types of Form Validation</h3>
<ol>
<li><strong>Client-Side Validation:</strong> The user's browser performs the checks before submission. How does the browser validate forms? Browsers use JavaScript, CSS, or HTML attributes to validate forms. The advantage of client-side validation is the quick error message the user receives when data is incorrect or incomplete. The response is quick and doesn't require validation from the server side. One of the disadvantages is that client-side validation can be bypassed by an experienced user. </li>
<li><strong>Server-Side Validation:</strong> The server checks the form data after submission. Server-side validation is more robust and secure. Performs double verification, and validates form data again, even if the client-side validation fails or is bypassed. The server-side validation is commonly done by using scripting languages like PHP or ASP.NET. </li>
</ol>
<p>Note that you can use either of the two or a combination of both.    </p>
<h3 id="heading-common-validation-techniques">Common Validation Techniques</h3>
<p>These are common HTML attributes that help you decide the pattern of form validation.</p>
<h4 id="heading-length-limits">Length Limits</h4>
<p>You can use the <code>maxlength</code> attribute to set the maximum number of characters an input field can hold.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Username"</span> <span class="hljs-attr">maxlength</span>=<span class="hljs-string">"20"</span> <span class="hljs-attr">required</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<h4 id="heading-required-fields">Required Fields</h4>
<p>Requires that certain input fields are filled before the form is submitted. The <code>&lt;required&gt;</code> attribute is used to perform this technique. An error message is displayed when the required field is not filled by the user. </p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Username"</span> <span class="hljs-attr">required</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Email"</span> <span class="hljs-attr">required</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<h4 id="heading-data-format">Data Format</h4>
<p>Ensures the data entered by the user follows the required format. The <code>&lt;input type="email"&gt;</code> type attribute set to email will require the user to enter the correct email format (for example: me@example.com) before form submission. </p>
<p>The same thing happens if the type attribute is set to number <code>&lt;input type="number"&gt;</code>, the user can only put data from 0-9.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Email"</span> <span class="hljs-attr">required</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<h4 id="heading-password-strength">Password Strength</h4>
<p>The <code>&lt;pattern=""&gt;</code> attribute is used to specify password complexity such as minimum length, and the inclusion of uppercase or lowercase letters, numbers, and special characters. </p>
<p>The <code>&lt;title=""&gt;</code> attribute displays the error message when the user hovers over the input field or when the entered password does not match the specified password format. The higher the password complexity, the higher the user account is protected from unauthorized access.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password"</span> <span class="hljs-attr">pattern</span>=<span class="hljs-string">"(?=.\d)(?=.[a-z])(?=.*[A-Z]).{8,}"</span> <span class="hljs-attr">title</span>=<span class="hljs-string">"Password must contain at least one number, one uppercase letter, one lowercase letter, and at least 8 or more characters"</span> <span class="hljs-attr">required</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<h4 id="heading-numeric-values">Numeric values</h4>
<p>You can set the range of numeric values to be entered by the user by using the <code>min</code> and <code>max</code> attributes. For example, to check if a user is within the specified age range:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"age"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"age"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Age"</span> <span class="hljs-attr">min</span>=<span class="hljs-string">"18"</span> <span class="hljs-attr">max</span>=<span class="hljs-string">"100"</span> <span class="hljs-attr">required</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>Having a good form validation practice helps to create forms with accurate data and reduces vulnerability to malicious attacks. </p>
<h2 id="heading-form-submission-and-methods">Form Submission and Methods</h2>
<p>When the submit button is clicked after filling out a form, your information is sent to the server for processing. This is called form submission. </p>
<h3 id="heading-methods-of-form-submission">Methods of Form Submission</h3>
<p>Form data is sent to the server using the <code>method</code> attribute. There are two commonly used methods:</p>
<h4 id="heading-get-method">GET Method</h4>
<p>With the <code>get</code> method <code>&lt;method="get"&gt;</code>, the form data is sent using the URL in the browser's address bar to the server. </p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"http://example.com"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"get"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span> /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Submit"</span> /&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>Using the above code sample, when the user enters a name (let's say the user's name is KC) in the input field named ''name'', and clicks the submit button, the form data will be sent to the server in the URL like this: "http://example.com?name=KC". </p>
<p>The GET method is not safe, as it is commonly used for sending small amounts of data that is not sensitive.  </p>
<h4 id="heading-post-method">POST Method</h4>
<p>The post method attribute <code>&lt;method=post&gt;</code> sends the form data in the body of the HTTP request to the server, rather than in the URL.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"http://example.com"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"get"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span> /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Submit"</span> /&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>Using the same code sample above, the POST method will send the form data to the server like this: "https://example.com/submit.php". </p>
<p>You'd should notice that the POST request does not contain the form data in the URL but rather points to the server-side script (submit.php) that will process the form data. </p>
<p>The sent form data is not visible. The POST request is used to submit sensitive information, like passwords, since the data is not visible in the URL, but rather sent in the HTTP body request.</p>
<h2 id="heading-how-to-style-html-forms">How to Style HTML Forms</h2>
<p>HTML forms can be styled using CSS, just like any other HTML element. You can do the following with CSS to match the design of your website:</p>
<ul>
<li><strong>Selectors</strong>: CSS selectors such as element selectors, class selectors, or ID selectors can be used to select specific elements in the HTML code for styling.</li>
<li><strong>Typography</strong>: Typography can be used to set the font-family, adjust the size, font-weight, and color of the text within the form element to enhance readability. </li>
<li><strong>Box Model</strong>: With the knowledge of CSS properties like padding, border, and margin, which affect the spacing and layout, you can style HTML elements.</li>
<li><strong>Colors and Backgrounds</strong>: The color of your text or background can be styled using the CSS properties like color and background-color (or background-image) respectively. </li>
<li><strong>Responsiveness</strong>: With media queries, you can make your form responsive and adapt to different screen sizes and devices. </li>
<li><strong>Layout</strong>: You can control the layout of a form to make it user-friendly with CSS properties like display, float, and positioning.</li>
</ul>
<h2 id="heading-best-practices-and-accessibility">Best Practices and Accessibility</h2>
<p>Like every other HTML document, ensure your form complies with web standards and is accessible to people with disabilities. For best practices and accessibility, take note of the following:</p>
<h3 id="heading-structures-and-semantics">Structures and Semantics</h3>
<ul>
<li>Always use proper semantic HTML elements (like  <code>&lt;form&gt;</code>, <code>&lt;input&gt;</code>, <code>&lt;label&gt;</code>, and so on) to structure not just forms but every other HTML document.</li>
<li>Nest elements properly and associate labels to their respective input field. </li>
<li>Make sure your input fields have the appropriate type attributes.</li>
</ul>
<h3 id="heading-error-handling-and-validation">Error Handling and Validation</h3>
<ul>
<li>Combine both client-side and server-side validation to avoid incorrect or incomplete data submission.</li>
<li>Use the appropriate attribute to display error messages when form submission fails or validation errors occur. </li>
</ul>
<h3 id="heading-responsive-design">Responsive Design</h3>
<ul>
<li>Your forms should be responsive and adapt to various screen sizes and devices.</li>
<li>Use CSS media queries to adjust your form layouts and styles based on the viewport size.</li>
</ul>
<h3 id="heading-design-and-contrast">Design and Contrast</h3>
<ul>
<li>Use fonts and colors that are easy to see.</li>
<li>The color contrast between text and background should ensure readability, especially for users with low vision. </li>
</ul>
<h3 id="heading-aria-roles-and-attributes">ARIA Roles and Attributes</h3>
<ul>
<li>ARIA (Accessible Rich Internet Application) roles and attributes improve accessibility for screen-reader users or other assistive technologies.</li>
<li>ARIA attributes ( <code>aria-labelledby</code>, <code>aria-describedby</code>, and <code>aria-invalid</code>) provide additional context and feedback for form elements.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Creating good HTML forms that meet web standards improve user interaction and experience on your website. By following the best practices and accessibility, developers can create forms that are user-friendly, and effective in collecting data from users. </p>
<p>You can learn more about HTML forms and responsive web design using <a target="_blank" href="https://www.freecodecamp.org/learn/2022/responsive-web-design/">freeCodeCamp's Responsive Web Design Certification</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Validate Forms in React – A Step-By-Step Tutorial for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ By Yazdun Fadali If you've ever worked with form validation in React, you know that it can quickly become messy and overwhelming. This is especially the case if you're just starting out with React.  In this tutorial, I will show you how to create reu... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-validate-forms-in-react/</link>
                <guid isPermaLink="false">66d4617a4a0edd9b48e835a3</guid>
                
                    <category>
                        <![CDATA[ Form validations ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 11 Apr 2023 19:08:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/thumbnail.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Yazdun Fadali</p>
<p>If you've ever worked with form validation in React, you know that it can quickly become messy and overwhelming. This is especially the case if you're just starting out with React. </p>
<p>In this tutorial, I will show you how to create reusable React components that allow you to build maintainable and clean forms. They'll easily be able to scale as your application grows. </p>
<p>You will also learn how to implement the popular react-hook-form library in your React application, which will simplify the process of adding form validations. And you'll learn how to implement reusable input validations across your entire React application, eliminating the need for repetitive code. </p>
<p>Get ready to level up your form handling skills in React with this ultimate guide. Let's dive in and master form validation in React.</p>
<h2 id="heading-heres-what-well-cover">Here's what we'll cover:</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-are-we-going-to-build">What Are We Going to Build?</a></li>
<li><a class="post-section-overview" href="#heading-getting-started">Getting Started</a></li>
<li><a class="post-section-overview" href="#heading-how-to-build-a-reusable-input-component">How to Build a Reusable Input Component</a></li>
<li><a class="post-section-overview" href="#heading-how-to-implement-input-validation-in-react">How to Implement Input Validation in React</a></li>
<li><a class="post-section-overview" href="#heading-how-to-display-appropriate-error-messages">How to Display Appropriate Error Messages</a></li>
<li><a class="post-section-overview" href="#heading-dynamic-input-validation">Dynamic Input Validation</a></li>
<li><a class="post-section-overview" href="#heading-how-to-implement-a-multiline-input-feature-in-the-input-component">How to Implement a Multiline Input Feature in the Input Component</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-successful-form-submission">How to Handle Successful Form Submission</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<p>Alright, let's dive in!</p>
<h2 id="heading-what-are-we-going-to-build"><strong>What Are We Going To Build?</strong></h2>
<p>In this tutorial, we will be building a minimalistic form that will allow users to input data. Here is a quick demo (<a target="_blank" href="https://react-fcc-forms.vercel.app/">live demo</a>):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/ezgif-3-767ff4d168.gif" alt="GIF displaying a React form with multiple input fields and a submit button" width="600" height="400" loading="lazy">
<em>Preview of the final project</em></p>
<p>We will leverage the power of react-hook-form, a popular form validation library in the React ecosystem, to handle form validation efficiently. We will be using Tailwind CSS for styling. </p>
<p>Don't worry if you're not familiar with Tailwind CSS or react-hook-form, as this tutorial is designed to be beginner-friendly. But having a basic understanding of React fundamentals will help you get the most out of this tutorial. </p>
<p>So let's get started and create a sleek and functional form in React!</p>
<h2 id="heading-getting-started">Getting Started</h2>
<p>To get started with this tutorial, I highly recommend using the <a target="_blank" href="https://github.com/Yazdun/react-fcc-forms/tree/starter">starter boilerplate</a> that I've prepared for you. It comes with all the necessary dependencies and folder structure, so you won't need to spend time setting up your project from scratch. </p>
<p>You can simply clone the starter boilerplate from the provided GitHub repository and follow along with the tutorial without any delays. This will allow you to focus on learning and implementing the concepts of form validation in React without getting bogged down by setup details.</p>
<ul>
<li>Starter Boilerplate: <a target="_blank" href="https://github.com/Yazdun/react-fcc-forms/tree/starter">View on GitHub</a></li>
<li>Final Version: <a target="_blank" href="https://github.com/Yazdun/react-fcc-forms/tree/main">View on GitHub</a></li>
</ul>
<p>After setting up the starter boilerplate and running it on your local machine, you should be able to see the following page. This page will serve as the starting point for our form validation project in React.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-90.png" alt="simple React web page with a heading that says 'Welcome to React Forms Tutorial'" width="600" height="400" loading="lazy">
<em>Starting page for our project</em></p>
<p>From here, we will gradually build upon the existing code and implement form validation using react-hook-form.</p>
<p>During this tutorial, we will be focusing on two key files: <code>src/components/Input.jsx</code> and <code>src/Form.jsx</code>.</p>
<p>In <code>src/components/Input.jsx</code>, we will create a reusable input React component. This component will serve as the foundation for our form, allowing users to input data in a clean and user-friendly manner. </p>
<p>We will implement input validation using react-hook-form, which will ensure that the data entered by users is valid before it is submitted.</p>
<p>Next, we will move on to <code>src/Form.jsx</code>, where we will handle form validation and submission. This file will serve as the main container for our form, and we will utilize react-hook-form to handle form validation efficiently.</p>
<p>By completing these two files, you will be able to create a beautiful and functional form with reusable input components and efficient form validation. So let's dive into the code and build our form validation project step by step.</p>
<h2 id="heading-how-to-build-a-reusable-input-component">How to Build a Reusable Input Component</h2>
<p>To start our form validation project, we will first create a reusable input component. Currently, our <code>src/components/Input.jsx</code> looks like this: </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-102.png" alt="An image showcasing the Visual Studio Code (VSCode) editor with a React code file open. The code file displays a simple React component named 'Input' that renders a div with the content 'input!'. Below the 'Input' component, there is another React component named 'InputError' that renders a div with the content 'error'." width="600" height="400" loading="lazy">
<em>Screenshot of <code>src/components/Input.jsx</code></em></p>
<p>The provided boilerplate code imports necessary dependencies such as <code>classnames</code>, <code>react-hook-form</code>, <code>framer-motion</code>, and <code>react-icons</code>. It defines a <code>Input</code> component, which currently renders a simple "input!" text. It also defines an <code>InputError</code> component which currently renders a "error" text. </p>
<p>Additionally, it includes a framer motion animation object <code>framer_error</code> with initial, animate, exit, and transition properties for error handling. This code will be further enhanced and customized to create a reusable input component for our form validation project.</p>
<p>Now it's time to dive into some coding! Our <code>Input</code> component will receive props that will determine the type of input to render, placeholder, id, and so on. We will utilize Tailwind CSS to add styling to our input component.  </p>
<p>Let's start enhancing our input component with props and Tailwind CSS. Add the following code to <code>src/components/Input.jsx</code>: </p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Input = <span class="hljs-function">(<span class="hljs-params">{ label, type, id, placeholder }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-col w-full gap-2"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex justify-between"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">{id}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"font-semibold capitalize"</span>&gt;</span>
          {label}
        <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">id</span>=<span class="hljs-string">{id}</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">{type}</span>
        <span class="hljs-attr">className</span>=<span class="hljs-string">"w-full p-5 font-medium border rounded-md border-slate-300 placeholder:opacity-60"</span>
        <span class="hljs-attr">placeholder</span>=<span class="hljs-string">{placeholder}</span>
      /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>The <code>Input</code> component receives <code>({ label, type, id, placeholder })</code> as props. These props are then used to dynamically render the Input component. </p>
<p>The <code>label</code> prop is used as the text content of the <code>label</code> element, and the <code>type</code>, <code>id</code>, and <code>placeholder</code> props are passed directly to the corresponding attributes of the <code>input</code> element using JSX syntax. This allows the <code>Input</code> component to be flexible and reusable, as different values can be passed in as props to customize its behavior based on the specific use case.</p>
<p>Now let's see our input component in action by adding the following code to <code>src/Form.jsx</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Form = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"container mt-5 text-center"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"grid gap-5 md:grid-cols-2"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Input</span>
          <span class="hljs-attr">label</span>=<span class="hljs-string">"name"</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
          <span class="hljs-attr">id</span>=<span class="hljs-string">"name"</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"type your name..."</span>
        /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Input</span>
          <span class="hljs-attr">label</span>=<span class="hljs-string">"password"</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span>
          <span class="hljs-attr">id</span>=<span class="hljs-string">"password"</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"type your password..."</span>
        /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>After adding the code to <code>src/Form.jsx</code>, open up your local server and you should be able to see the resulting page with the input component: </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-104.png" alt="showing a simple React web page with two input fields" width="600" height="400" loading="lazy">
<em>Preview of what we've built so far</em></p>
<p>Great job 🎉! You have successfully created a re-usable Input component for your app. Now, let's take it a step further and add some exciting validation features to enhance our app's functionality.</p>
<h2 id="heading-how-to-implement-input-validation-in-react">How to Implement Input Validation in React</h2>
<p>Now it's time to implement react-hook-form and add input validation to our application.</p>
<p>First, we need to modify our <code>src/Form.jsx</code> file to utilize the <code>useForm</code> hook and <code>FormProvider</code> component provided by react-hook-form. These tools will allow us to easily handle form validation and submission in our React application. </p>
<p>Let's dive into the details of how to use them effectively. Add the following code to the <code>src/Form.jsx</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Form = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> methods = useForm()

  <span class="hljs-keyword">const</span> onSubmit = methods.handleSubmit(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data)
  })

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">FormProvider</span> {<span class="hljs-attr">...methods</span>}&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span>
        <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{e</span> =&gt;</span> e.preventDefault()}
        noValidate
        className="container"
      &gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"grid gap-5 md:grid-cols-2"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span>
            <span class="hljs-attr">label</span>=<span class="hljs-string">"name"</span>
            <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
            <span class="hljs-attr">id</span>=<span class="hljs-string">"name"</span>
            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"type your name..."</span>
          /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span>
            <span class="hljs-attr">label</span>=<span class="hljs-string">"password"</span>
            <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span>
            <span class="hljs-attr">id</span>=<span class="hljs-string">"password"</span>
            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"type your password..."</span>
          /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"mt-5"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
            <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onSubmit}</span>
            <span class="hljs-attr">className</span>=<span class="hljs-string">"flex items-center gap-1 p-5 font-semibold text-white bg-blue-600 rounded-md hover:bg-blue-800"</span>
          &gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">GrMail</span> /&gt;</span>
            Submit Form
          <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">FormProvider</span>&gt;</span></span>
  )
}
</code></pre>
<p>There's a lot happening in this section, but no worries – I'll guide you through it. First, you use <code>const methods = useForm()</code> to set up the form methods from <code>react-hook-form</code> for form management. </p>
<p>Next, you create a custom <code>onSubmit</code> function that utilizes the <code>methods</code> to handle form submission, which we'll run when the form is successfully submitted.</p>
<p>Then you use the <code>FormProvider</code> component provided by <code>react-hook-form</code> to wrap your form, allowing you to access the form's context inside your <code>Input</code> component later on. Then you utilize the JavaScript spread operator to pass all the <code>useForm</code> methods to the <code>FormProvider</code>.</p>
<p>Inside the <code>FormProvider</code>, you create a form and pass <code>noValidate</code> to indicate that you want to rely entirely on <code>react-hook-form</code> for form validation. You also prevent the form's default behavior by passing <code>onSubmit={e =&gt; e.preventDefault()}</code>. </p>
<p>Instead of attaching the <code>onSubmit</code> function to the form, you create a custom button at the end of the file and pass the custom <code>onSubmit</code> function to it to handle form submission.</p>
<p>Next, you need to update the Input component to enable form validation. Add the following code to <code>src/components/Input.jsx</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Input = <span class="hljs-function">(<span class="hljs-params">{ label, type, id, placeholder }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> { register } = useFormContext()

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-col w-full gap-2"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex justify-between"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">{id}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"font-semibold capitalize"</span>&gt;</span>
          {label}
        <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">id</span>=<span class="hljs-string">{id}</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">{type}</span>
        <span class="hljs-attr">className</span>=<span class="hljs-string">"w-full p-5 font-medium border rounded-md border-slate-300 placeholder:opacity-60"</span>
        <span class="hljs-attr">placeholder</span>=<span class="hljs-string">{placeholder}</span>
        {<span class="hljs-attr">...register</span>(<span class="hljs-attr">label</span>, {
          <span class="hljs-attr">required:</span> {
            <span class="hljs-attr">value:</span> <span class="hljs-attr">true</span>,
            <span class="hljs-attr">message:</span> '<span class="hljs-attr">required</span>',
          },
        })}
      /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>You are retrieving the <code>register</code> function from the <code>useFormContext</code> hook provided by react-hook-form, which is used to register an input field with the library, allowing it to handle validation. This function will be passed to the input element. </p>
<p>The <code>register</code> function takes two arguments. The first argument is the name of the input, which will be used as a key within your form context to access the input's value or retrieve its error message. </p>
<p>The second argument is an object that contains the input's validations. React-hook-form supports a wide range of validations, and you can refer to their <a target="_blank" href="https://react-hook-form.com/api/">documentation</a> for more information. For now, we are only using the <code>required</code> validation.</p>
<p>Now open up your local server, you can enter values into all the inputs. But the form cannot be submitted until all inputs are filled, as they have required validation. Upon successful submission, the custom <code>onSubmit</code> function will execute and log the form data into the browser console:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-107.png" alt="a form in a React web page, with the Chrome console open and displaying a submitted form data object." width="600" height="400" loading="lazy">
<em>Successful form submission</em></p>
<p>Congratulations! 🎉 You've successfully completed this challenging section. Great job! Now, let's take it a step further and enhance our custom Input component by learning how to pass dynamic validations and display appropriate error messages.</p>
<h2 id="heading-how-to-display-appropriate-error-messages">How to Display Appropriate Error Messages</h2>
<p>Before going any further, let's get error messages out of the way. Add this code to <code>src/components/Input.jsx</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Input = <span class="hljs-function">(<span class="hljs-params">{ label, type, id, placeholder }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> { register } = useFormContext()

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-col w-full gap-2"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex justify-between"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">{id}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"font-semibold capitalize"</span>&gt;</span>
          {label}
        <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">id</span>=<span class="hljs-string">{id}</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">{type}</span>
        <span class="hljs-attr">className</span>=<span class="hljs-string">"w-full p-5 font-medium border rounded-md border-slate-300 placeholder:opacity-60"</span>
        <span class="hljs-attr">placeholder</span>=<span class="hljs-string">{placeholder}</span>
        {<span class="hljs-attr">...register</span>(<span class="hljs-attr">label</span>, {
          <span class="hljs-attr">required:</span> {
            <span class="hljs-attr">value:</span> <span class="hljs-attr">true</span>,
            <span class="hljs-attr">message:</span> '<span class="hljs-attr">required</span>',
          },
        })}
      /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">const</span> InputError = <span class="hljs-function">(<span class="hljs-params">{ message }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">motion.p</span>
      <span class="hljs-attr">className</span>=<span class="hljs-string">"flex items-center gap-1 px-2 font-semibold text-red-500 bg-red-100 rounded-md"</span>
      {<span class="hljs-attr">...framer_error</span>}
    &gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">MdError</span> /&gt;</span>
      {message}
    <span class="hljs-tag">&lt;/<span class="hljs-name">motion.p</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">const</span> framer_error = {
  <span class="hljs-attr">initial</span>: { <span class="hljs-attr">opacity</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">y</span>: <span class="hljs-number">10</span> },
  <span class="hljs-attr">animate</span>: { <span class="hljs-attr">opacity</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">y</span>: <span class="hljs-number">0</span> },
  <span class="hljs-attr">exit</span>: { <span class="hljs-attr">opacity</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">y</span>: <span class="hljs-number">10</span> },
  <span class="hljs-attr">transition</span>: { <span class="hljs-attr">duration</span>: <span class="hljs-number">0.2</span> },
}
</code></pre>
<p>Let me explain to you what's going on here. First of all, you've created a custom component called <code>InputError</code> which recieves a message as a prop and display it. </p>
<p>You are using framer motion to add smooth transitions to this component. Framer Motion is a library which allows us to add cool animations to our react components.</p>
<p>Now let's update your <code>Input</code> component so you can make use of <code>InputError</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { findInputError, isFormInvalid } <span class="hljs-keyword">from</span> <span class="hljs-string">'../utils'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Input = <span class="hljs-function">(<span class="hljs-params">{ label, type, id, placeholder }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> {
    register,
    <span class="hljs-attr">formState</span>: { errors },
  } = useFormContext()

  <span class="hljs-keyword">const</span> inputError = findInputError(errors, label)
  <span class="hljs-keyword">const</span> isInvalid = isFormInvalid(inputError)

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-col w-full gap-2"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex justify-between"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">{id}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"font-semibold capitalize"</span>&gt;</span>
          {label}
        <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">AnimatePresence</span> <span class="hljs-attr">mode</span>=<span class="hljs-string">"wait"</span> <span class="hljs-attr">initial</span>=<span class="hljs-string">{false}</span>&gt;</span>
          {isInvalid &amp;&amp; (
            <span class="hljs-tag">&lt;<span class="hljs-name">InputError</span>
              <span class="hljs-attr">message</span>=<span class="hljs-string">{inputError.error.message}</span>
              <span class="hljs-attr">key</span>=<span class="hljs-string">{inputError.error.message}</span>
            /&gt;</span>
          )}
        <span class="hljs-tag">&lt;/<span class="hljs-name">AnimatePresence</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">id</span>=<span class="hljs-string">{id}</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">{type}</span>
        <span class="hljs-attr">className</span>=<span class="hljs-string">"w-full p-5 font-medium border rounded-md border-slate-300 placeholder:opacity-60"</span>
        <span class="hljs-attr">placeholder</span>=<span class="hljs-string">{placeholder}</span>
        {<span class="hljs-attr">...register</span>(<span class="hljs-attr">label</span>, {
          <span class="hljs-attr">required:</span> {
            <span class="hljs-attr">value:</span> <span class="hljs-attr">true</span>,
            <span class="hljs-attr">message:</span> '<span class="hljs-attr">required</span>',
          },
        })}
      /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>You're using the <code>useFormContext</code> hook to retrieve the formState, which contains all the form error messages. But in order to display the errors properly, you need to extract the relevant errors for each input. </p>
<p>To simplify this process, I've already written a utility function called <code>findInputError.js</code> in the <code>src/utils</code> directory. This function takes an errors object and the input's name as arguments and returns the related errors. Then we pass the filtered error to the <code>InputError</code> component. You can check out this utility function for reference:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-108.png" alt="JavaScript function named 'findInputErrors' displayed in Visual Studio Code." width="600" height="400" loading="lazy">
<em>Screenshot of <code>src/utils/findInputError.js</code></em></p>
<p>In order to display an error message, the form must be invalid. To determine if the form is invalid or not, I've also written a simple utility function for you that takes an error object as input and returns true if the form is not valid. You can check out this utility function for reference:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-109.png" alt="JavaScript function named 'isFormInvalid' displayed in Visual Studio Code." width="600" height="400" loading="lazy">
<em>Screenshot of <code>src/utils/isFormInvalid.js</code></em></p>
<p>Additionally, you may have noticed that we've used the <code>AnimatePresence</code> component from the Framer Motion library to wrap the <code>InputError</code> component. We did this to add animation to the unmounting of InputError, providing a smooth user experience. While this is optional, I thought it would be a nice touch to add to this project. </p>
<p>Here is what your project looks like so far:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/ezgif-5-091f434a4a-1.gif" alt="GIF showcasing a React web page with a form that is being submitted by a user, but errors are displayed." width="600" height="400" loading="lazy">
<em>Preview of what we've built so far</em></p>
<h2 id="heading-dynamic-input-validation">Dynamic Input Validation</h2>
<h3 id="heading-part-1">Part 1</h3>
<p>You have made excellent progress so far! Currently, we have hard-coded validations into the Input component, but you may need different types of validations for each input in the future. </p>
<p>Let's update the Input component to receive a validation object as a prop and pass it to the react-hook-form <code>register</code> function. Let's modify <code>src/components/Input.jsx</code> like this:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Input = <span class="hljs-function">(<span class="hljs-params">{ label, type, id, placeholder, validation, name }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> {
    register,
    <span class="hljs-attr">formState</span>: { errors },
  } = useFormContext()

  <span class="hljs-keyword">const</span> inputError = findInputError(errors, name)
  <span class="hljs-keyword">const</span> isInvalid = isFormInvalid(inputError)

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-col w-full gap-2"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex justify-between"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">{id}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"font-semibold capitalize"</span>&gt;</span>
          {label}
        <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">AnimatePresence</span> <span class="hljs-attr">mode</span>=<span class="hljs-string">"wait"</span> <span class="hljs-attr">initial</span>=<span class="hljs-string">{false}</span>&gt;</span>
          {isInvalid &amp;&amp; (
            <span class="hljs-tag">&lt;<span class="hljs-name">InputError</span>
              <span class="hljs-attr">message</span>=<span class="hljs-string">{inputError.error.message}</span>
              <span class="hljs-attr">key</span>=<span class="hljs-string">{inputError.error.message}</span>
            /&gt;</span>
          )}
        <span class="hljs-tag">&lt;/<span class="hljs-name">AnimatePresence</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">id</span>=<span class="hljs-string">{id}</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">{type}</span>
        <span class="hljs-attr">className</span>=<span class="hljs-string">"w-full p-5 font-medium border rounded-md border-slate-300 placeholder:opacity-60"</span>
        <span class="hljs-attr">placeholder</span>=<span class="hljs-string">{placeholder}</span>
        {<span class="hljs-attr">...register</span>(<span class="hljs-attr">name</span>, <span class="hljs-attr">validation</span>)}
      /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>There haven't been many changes. You have added two new props to our custom Input component, a validation object and a name prop. We will use the name prop instead of the label to register our input, and also utilize it to find the related input errors. </p>
<p>You've also passed the validation prop to the register function instead of hard-coding it. This allows you to have dynamic validations for your inputs.</p>
<p>Now let's modify <code>src/Form.jsx</code> and pass dynamic validations to our custom Input component:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Form = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> methods = useForm()

  <span class="hljs-keyword">const</span> onSubmit = methods.handleSubmit(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data)
  })

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">FormProvider</span> {<span class="hljs-attr">...methods</span>}&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span>
        <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{e</span> =&gt;</span> e.preventDefault()}
        noValidate
        autoComplete="off"
        className="container"
      &gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"grid gap-5 md:grid-cols-2"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span>
            <span class="hljs-attr">label</span>=<span class="hljs-string">"name"</span>
            <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span>
            <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
            <span class="hljs-attr">id</span>=<span class="hljs-string">"name"</span>
            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"type your name..."</span>
            <span class="hljs-attr">validation</span>=<span class="hljs-string">{{</span>
              <span class="hljs-attr">required:</span> {
                <span class="hljs-attr">value:</span> <span class="hljs-attr">true</span>,
                <span class="hljs-attr">message:</span> '<span class="hljs-attr">required</span>',
              },
            }}
          /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span>
            <span class="hljs-attr">label</span>=<span class="hljs-string">"password"</span>
            <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span>
            <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span>
            <span class="hljs-attr">id</span>=<span class="hljs-string">"password"</span>
            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"type your password..."</span>
            <span class="hljs-attr">validation</span>=<span class="hljs-string">{{</span>
              <span class="hljs-attr">required:</span> {
                <span class="hljs-attr">value:</span> <span class="hljs-attr">true</span>,
                <span class="hljs-attr">message:</span> '<span class="hljs-attr">required</span>',
              },
              <span class="hljs-attr">minLength:</span> {
                <span class="hljs-attr">value:</span> <span class="hljs-attr">6</span>,
                <span class="hljs-attr">message:</span> '<span class="hljs-attr">min</span> <span class="hljs-attr">6</span> <span class="hljs-attr">characters</span>',
              },
            }}
          /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"mt-5"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
            <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onSubmit}</span>
            <span class="hljs-attr">className</span>=<span class="hljs-string">"flex items-center gap-1 p-5 font-semibold text-white bg-blue-600 rounded-md hover:bg-blue-800"</span>
          &gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">GrMail</span> /&gt;</span>
            Submit Form
          <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">FormProvider</span>&gt;</span></span>
  )
}
</code></pre>
<p>You are now passing different validations to each Input component. This allows each Input to dynamically validate its value based on the provided validation object.</p>
<h3 id="heading-part-2">Part 2</h3>
<p>In the previous section, you learned how to pass dynamic validation to your custom Input component. </p>
<p>While this approach works, it may not be efficient if you need to use the password or name Input component in multiple places, such as the sign-up page, login page, and profile page. </p>
<p>Copy-pasting the same code in multiple locations can lead to maintenance issues, especially if you need to make changes to the validation logic later on. </p>
<p>But there is a solution to this problem. You can isolate the input validations into a separate object and then pass that object to the custom Input component using JavaScript spread operators. This approach allows you to centralize the validation logic, making it easier to manage and update across your application, even as it scales. </p>
<p>Let's update <code>src/Form.jsx</code> and see how this works in action: </p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Form = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> methods = useForm()

  <span class="hljs-keyword">const</span> onSubmit = methods.handleSubmit(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data)
  })

  <span class="hljs-keyword">const</span> name_validation = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'name'</span>,
    <span class="hljs-attr">label</span>: <span class="hljs-string">'name'</span>,
    <span class="hljs-attr">type</span>: <span class="hljs-string">'text'</span>,
    <span class="hljs-attr">id</span>: <span class="hljs-string">'name'</span>,
    <span class="hljs-attr">placeholder</span>: <span class="hljs-string">'write your name ...'</span>,
    <span class="hljs-attr">validation</span>: {
      <span class="hljs-attr">required</span>: {
        <span class="hljs-attr">value</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">'required'</span>,
      },
      <span class="hljs-attr">maxLength</span>: {
        <span class="hljs-attr">value</span>: <span class="hljs-number">30</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">'30 characters max'</span>,
      },
    },
  }

  <span class="hljs-keyword">const</span> password_validation = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'password'</span>,
    <span class="hljs-attr">label</span>: <span class="hljs-string">'password'</span>,
    <span class="hljs-attr">type</span>: <span class="hljs-string">'password'</span>,
    <span class="hljs-attr">id</span>: <span class="hljs-string">'password'</span>,
    <span class="hljs-attr">placeholder</span>: <span class="hljs-string">'type password ...'</span>,
    <span class="hljs-attr">validation</span>: {
      <span class="hljs-attr">required</span>: {
        <span class="hljs-attr">value</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">'required'</span>,
      },
      <span class="hljs-attr">minLength</span>: {
        <span class="hljs-attr">value</span>: <span class="hljs-number">6</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">'min 6 characters'</span>,
      },
    },
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">FormProvider</span> {<span class="hljs-attr">...methods</span>}&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span>
        <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{e</span> =&gt;</span> e.preventDefault()}
        noValidate
        autoComplete="off"
        className="container"
      &gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"grid gap-5 md:grid-cols-2"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> {<span class="hljs-attr">...name_validation</span>} /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> {<span class="hljs-attr">...password_validation</span>} /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"mt-5"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
            <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onSubmit}</span>
            <span class="hljs-attr">className</span>=<span class="hljs-string">"flex items-center gap-1 p-5 font-semibold text-white bg-blue-600 rounded-md hover:bg-blue-800"</span>
          &gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">GrMail</span> /&gt;</span>
            Submit Form
          <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">FormProvider</span>&gt;</span></span>
  )
}
</code></pre>
<p>Great! Using a separate object to store input props and validations, and then passing it to the custom Input component using spread operators can help you to centralize and manage the validation logic in your application. </p>
<p>This approach can make it easier to update or modify the validations in one place, instead of having to make changes in multiple locations. It can also improve code reusability and reduce duplication, especially when using the same input component in different parts of your application. </p>
<p>In order to keep the input validation logic separate from the main component, I have created an input validation file in the boilerplate code located at <code>src/utils/inputValidations</code>. This file contains various pre-defined input validators that you can utilize in your application. </p>
<p>You can easily import these validators wherever needed and pass them to the custom Input component using JavaScript spread operators. This approach allows for centralized management of input validations, making it easy to update and reuse them across different parts of your application. </p>
<p>By leveraging the input validation file, you can keep your code organized, maintainable, and scalable, and ensure consistency in input validation throughout your application. </p>
<p>Let's modify <code>src/Form.jsx</code> and use our custom validators:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Form = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> methods = useForm()

  <span class="hljs-keyword">const</span> onSubmit = methods.handleSubmit(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data)
  })

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">FormProvider</span> {<span class="hljs-attr">...methods</span>}&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span>
        <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{e</span> =&gt;</span> e.preventDefault()}
        noValidate
        autoComplete="off"
        className="container"
      &gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"grid gap-5 md:grid-cols-2"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> {<span class="hljs-attr">...name_validation</span>} /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> {<span class="hljs-attr">...email_validation</span>} /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> {<span class="hljs-attr">...num_validation</span>} /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> {<span class="hljs-attr">...password_validation</span>} /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"mt-5"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
            <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onSubmit}</span>
            <span class="hljs-attr">className</span>=<span class="hljs-string">"flex items-center gap-1 p-5 font-semibold text-white bg-blue-600 rounded-md hover:bg-blue-800"</span>
          &gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">GrMail</span> /&gt;</span>
            Submit Form
          <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">FormProvider</span>&gt;</span></span>
  )
}
</code></pre>
<p>Now your code becomes much cleaner and more maintainable. One of the major benefits is that you can now easily use the same input validator at multiple places in your application without duplicating code. </p>
<p>This means that if you need to update the validation logic, you only need to make changes in one place, and the changes will be applied everywhere the input validator is used. This makes managing input validations more efficient and minimizes the risk of inconsistencies across different parts of your application. It's an awesome approach that promotes code reusability and scalability.</p>
<h2 id="heading-how-to-implement-a-multiline-input-feature-in-the-input-component">How to Implement a Multiline Input Feature in the Input Component</h2>
<p>Congratulations on your progress so far! With the challenging parts behind us, we can now focus on adding a straightforward feature to our custom Input component. This feature will allow us to easily handle multiline inputs in our application. </p>
<p>Add the following code to <code>src/components/Input.jsx</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Input = <span class="hljs-function">(<span class="hljs-params">{
  name,
  label,
  type,
  id,
  placeholder,
  validation,
  multiline,
  className,
}</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> {
    register,
    <span class="hljs-attr">formState</span>: { errors },
  } = useFormContext()

  <span class="hljs-keyword">const</span> inputErrors = findInputError(errors, name)
  <span class="hljs-keyword">const</span> isInvalid = isFormInvalid(inputErrors)

  <span class="hljs-keyword">const</span> input_tailwind =
    <span class="hljs-string">'p-5 font-medium rounded-md w-full border border-slate-300 placeholder:opacity-60'</span>

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{cn(</span>'<span class="hljs-attr">flex</span> <span class="hljs-attr">flex-col</span> <span class="hljs-attr">w-full</span> <span class="hljs-attr">gap-2</span>', <span class="hljs-attr">className</span>)}&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex justify-between"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">{id}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"font-semibold capitalize"</span>&gt;</span>
          {label}
        <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">AnimatePresence</span> <span class="hljs-attr">mode</span>=<span class="hljs-string">"wait"</span> <span class="hljs-attr">initial</span>=<span class="hljs-string">{false}</span>&gt;</span>
          {isInvalid &amp;&amp; (
            <span class="hljs-tag">&lt;<span class="hljs-name">InputError</span>
              <span class="hljs-attr">message</span>=<span class="hljs-string">{inputErrors.error.message}</span>
              <span class="hljs-attr">key</span>=<span class="hljs-string">{inputErrors.error.message}</span>
            /&gt;</span>
          )}
        <span class="hljs-tag">&lt;/<span class="hljs-name">AnimatePresence</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      {multiline ? (
        <span class="hljs-tag">&lt;<span class="hljs-name">textarea</span>
          <span class="hljs-attr">id</span>=<span class="hljs-string">{id}</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">{type}</span>
          <span class="hljs-attr">className</span>=<span class="hljs-string">{cn(input_tailwind,</span> '<span class="hljs-attr">min-h-</span>[<span class="hljs-attr">10rem</span>] <span class="hljs-attr">max-h-</span>[<span class="hljs-attr">20rem</span>] <span class="hljs-attr">resize-y</span>')}
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">{placeholder}</span>
          {<span class="hljs-attr">...register</span>(`${<span class="hljs-attr">name</span>}`, <span class="hljs-attr">validation</span>)}
        &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">textarea</span>&gt;</span>
      ) : (
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">id</span>=<span class="hljs-string">{id}</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">{type}</span>
          <span class="hljs-attr">className</span>=<span class="hljs-string">{cn(input_tailwind)}</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">{placeholder}</span>
          {<span class="hljs-attr">...register</span>(<span class="hljs-attr">name</span>, <span class="hljs-attr">validation</span>)}
        /&gt;</span>
      )}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>You have made some modifications to the Input component code. You have added two new props: <code>multiline</code>, which determines whether the component should render an input or a textarea, and <code>className</code>, which allows us to customize the Input component with custom Tailwind utility classes if needed. </p>
<p>To merge all the utility classes together, you are using a JavaScript library called classnames, which provides a clean syntax for combining multiple class names. Now let's add a multiline input to <code>src/Form.jsx</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Form = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> methods = useForm()

  <span class="hljs-keyword">const</span> onSubmit = methods.handleSubmit(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data)
  })

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">FormProvider</span> {<span class="hljs-attr">...methods</span>}&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span>
        <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{e</span> =&gt;</span> e.preventDefault()}
        noValidate
        autoComplete="off"
        className="container"
      &gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"grid gap-5 md:grid-cols-2"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> {<span class="hljs-attr">...name_validation</span>} /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> {<span class="hljs-attr">...email_validation</span>} /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> {<span class="hljs-attr">...num_validation</span>} /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> {<span class="hljs-attr">...password_validation</span>} /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> {<span class="hljs-attr">...desc_validation</span>} <span class="hljs-attr">className</span>=<span class="hljs-string">"md:col-span-2"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"mt-5"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
            <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onSubmit}</span>
            <span class="hljs-attr">className</span>=<span class="hljs-string">"flex items-center gap-1 p-5 font-semibold text-white bg-blue-600 rounded-md hover:bg-blue-800"</span>
          &gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">GrMail</span> /&gt;</span>
            Submit Form
          <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">FormProvider</span>&gt;</span></span>
  )
}
</code></pre>
<p>The <code>{...desc_validation}</code> object has <code>multiline</code> set to true, which allows it to render a textarea instead of an input. Also, you've passed a custom classname to this particular Input component, ensuring it always fills the full width. If you open your local server, you will see the output as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/ezgif-1-ee09a58a83.gif" alt="GIF illustrating a React web page with a form that contains multiple input fields. The user attempts to submit the form, but error messages are displayed near some of the input fields, indicating that there are validation issues with the entered data. The form cannot be submitted until the errors are fixed" width="600" height="400" loading="lazy">
<em>Preview of what we've built so far</em></p>
<p>With that, your Input component is officially completed! 🎉 You've successfully created a maintainable and reusable component that you can use in your own React applications. </p>
<p>Before we wrap up, there's one last topic to discuss which is successful form submission. Let's get into that.</p>
<h2 id="heading-how-to-handle-successful-form-submission">How to Handle Successful Form Submission</h2>
<p>In an ideal scenario, we would like to display a success message when a form submission is successful, process the submitted data, and reset the form. In this section, we will cover how to handle these actions.</p>
<p>First, let's update <code>src/Form.jsx</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Form = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> methods = useForm()
  <span class="hljs-keyword">const</span> [success, setSuccess] = useState(<span class="hljs-literal">false</span>)

  <span class="hljs-keyword">const</span> onSubmit = methods.handleSubmit(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data)
    methods.reset()
    setSuccess(<span class="hljs-literal">true</span>)
  })

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">FormProvider</span> {<span class="hljs-attr">...methods</span>}&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span>
        <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{e</span> =&gt;</span> e.preventDefault()}
        noValidate
        autoComplete="off"
        className="container"
      &gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"grid gap-5 md:grid-cols-2"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> {<span class="hljs-attr">...name_validation</span>} /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> {<span class="hljs-attr">...email_validation</span>} /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> {<span class="hljs-attr">...num_validation</span>} /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> {<span class="hljs-attr">...password_validation</span>} /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> {<span class="hljs-attr">...desc_validation</span>} <span class="hljs-attr">className</span>=<span class="hljs-string">"md:col-span-2"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"mt-5"</span>&gt;</span>
          {success &amp;&amp; (
            <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex items-center gap-1 mb-5 font-semibold text-green-500"</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">BsFillCheckSquareFill</span> /&gt;</span> Form has been submitted successfully
            <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          )}
          <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
            <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onSubmit}</span>
            <span class="hljs-attr">className</span>=<span class="hljs-string">"flex items-center gap-1 p-5 font-semibold text-white bg-blue-600 rounded-md hover:bg-blue-800"</span>
          &gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">GrMail</span> /&gt;</span>
            Submit Form
          <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">FormProvider</span>&gt;</span></span>
  )
}
</code></pre>
<p>We have utilized the <code>useState</code> hook to create a state variable called <code>success</code>, which is initially set to false. </p>
<p>Upon successful form submission, we update the state value to true using the <code>setSuccess</code> function. When <code>success</code> is true, a paragraph with the message "Form has been submitted successfully" will be displayed. Also, we are utilizing the <code>methods</code> object from the <code>react-hook-form</code> library to reset the form using <code>methods.reset()</code> after a successful submission.</p>
<p>We have also included a console.log statement to display the submitted data in the console after form submission. You can utilize this data as needed, such as sending it to a backend server, storing it in local storage, and so on. </p>
<p>But for the purpose of simplicity in this tutorial, we are solely logging the submitted data in the console, which will be displayed in the following format:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-127.png" alt="a React web page with a form, along with the Chrome console open and displaying the submitted data." width="600" height="400" loading="lazy">
<em>Screenshot of successful form submission</em></p>
<p>At this point, we have a fully functional form that includes a custom Input component and reusable Input validations. This form gracefully handles different form states, whether it's a failed submission or a successful one.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, we have successfully built a maintainable and reusable form in React using the react-hook-form library. We created a custom Input component that can handle various types of inputs with validation. We also implemented error handling for failed form submissions and displayed success messages for successful submissions.</p>
<p>Throughout the tutorial, you learned how to use react-hook-form to manage form state, handle form submissions, reset forms, and validate form inputs. You also utilized the power of Tailwind CSS for styling and customization, including passing custom classnames to our Input component.</p>
<p>By following best practices and leveraging the features of react-hook-form, you were able to create a clean and efficient form that can be easily integrated into any React application. </p>
<p>This form can serve as a foundation for more complex forms with additional functionality, such as backend API integration, form data persistence, and form validation with custom rules.</p>
<p>I hope this tutorial has been helpful in understanding how to build a form with react-hook-form and Tailwind CSS. Feel free to experiment and extend the functionalities of this form to suit your specific requirements.</p>
<p>You can follow me on <a target="_blank" href="https://twitter.com/Yazdun">Twitter</a> where I share more useful tips on web development. Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Add Form Validation in React Forms using React Hook Form ]]>
                </title>
                <description>
                    <![CDATA[ By Nishant Kumar Creating forms with proper validation can be tough and problematic. But in this blog post, I will show you how to do so in a simple and straightforward way. We'll learn how to add validation in a form using React and React Hook Form.... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/add-form-validation-in-react-app-with-react-hook-form/</link>
                <guid isPermaLink="false">66d46041ffe6b1f641b5fa36</guid>
                
                    <category>
                        <![CDATA[ Form validations ]]>
                    </category>
                
                    <category>
                        <![CDATA[ forms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 12 Oct 2021 20:52:04 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/10/How-to-Build-a-Weather-Application-using-React--19--1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Nishant Kumar</p>
<p>Creating forms with proper validation can be tough and problematic. But in this blog post, I will show you how to do so in a simple and straightforward way.</p>
<p>We'll learn how to add validation in a form using React and React Hook Form.</p>
<h3 id="heading-heres-an-interactive-scrim-about-how-to-add-form-validation-in-react-forms">Here's an interactive scrim about how to add form validation in React forms:</h3>
<div class="embed-wrapper"><iframe src="https://scrimba.com/scrim/cobc44a7ba60db603359ae530?embed=freecodecamp,mini-header" width="100%" height="480" title="Embedded content" loading="lazy"></iframe></div>

<h2 id="heading-how-to-create-a-form-in-react">How to Create a Form in React</h2>
<p>We will start by creating a form using the Semantic UI library. So, let's install it using one of the following commands:</p>
<pre><code class="lang-bash">yarn add semantic-ui-react semantic-ui-css
<span class="hljs-comment">## Or NPM</span>
npm install semantic-ui-react semantic-ui-css
</code></pre>
<p>After you've installed it, you need to import the package into your index.js file, which is your application's main entry file.</p>
<pre><code><span class="hljs-keyword">import</span> <span class="hljs-string">'semantic-ui-css/semantic.min.css'</span>
</code></pre><p>Then we need a form with four fields. So, let's create it with the following code:</p>
<pre><code><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { Form, Button } <span class="hljs-keyword">from</span> <span class="hljs-string">'semantic-ui-react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">FormValidation</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Form</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">Form.Field</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>First Name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'First Name'</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> /&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">Form.Field</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">Form.Field</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Last Name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'Last Name'</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> /&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">Form.Field</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">Form.Field</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Email<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'Email'</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> /&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">Form.Field</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">Form.Field</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Password<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'Password'</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> /&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">Form.Field</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'submit'</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">Form</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
}
</code></pre><p>We have a form now. It has four fields, which are First Name, Last Name, Email, and Password. It also has a Submit button so users can submit the form.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/Screenshot-2021-10-09-103510.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-install-react-hook-form">How to Install React Hook Form</h3>
<p>To install <a target="_blank" href="https://react-hook-form.com/">React Hook Form</a>, use the command below:</p>
<pre><code>npm install react-hook-form
</code></pre><p>You can read the documentation if you want to learn more about the library. We can use it for both React web and React Native applications.</p>
<p>The first thing we need to do here is get the data from the input fields and display them into the console. We need to import the package first:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useForm } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-hook-form'</span>;
</code></pre>
<p>Then, we need to destructure the <strong><code>useForm</code></strong> object in our app, like this:</p>
<pre><code><span class="hljs-keyword">const</span> { register, handleSubmit, <span class="hljs-attr">formState</span>: { errors } } = useForm();
</code></pre><p>Now, we are going to use the <strong><code>register</code></strong> property from the object <strong><code>useForm</code></strong> to register our form fields. It will be something like this:</p>
<pre><code class="lang-jsx">&lt;Form.Field&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>First Name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'First Name'</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> {<span class="hljs-attr">...register</span>('<span class="hljs-attr">firstName</span>')} /&gt;</span></span>
&lt;/Form.Field&gt;;
</code></pre>
<p>Now the First Name form field has the key of firstName. As you can see, we have declared it in the <strong>register</strong>. Repeat this for all other fields.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { Form, Button } <span class="hljs-keyword">from</span> <span class="hljs-string">'semantic-ui-react'</span>;
<span class="hljs-keyword">import</span> { useForm } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-hook-form'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">FormValidation</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> {
    register,
    handleSubmit,
    <span class="hljs-attr">formState</span>: { errors },
  } = useForm();
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Form</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Form.Field</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>First Name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'First Name'</span>
            <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
            {<span class="hljs-attr">...register</span>('<span class="hljs-attr">firstName</span>')}
          /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Form.Field</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Form.Field</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Last Name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'Last Name'</span>
            <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
            {<span class="hljs-attr">...register</span>('<span class="hljs-attr">lastName</span>')}
          /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Form.Field</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Form.Field</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Email<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'Email'</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'email'</span> {<span class="hljs-attr">...register</span>('<span class="hljs-attr">email</span>')} /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Form.Field</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Form.Field</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Password<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'Password'</span>
            <span class="hljs-attr">type</span>=<span class="hljs-string">'password'</span>
            {<span class="hljs-attr">...register</span>('<span class="hljs-attr">password</span>')}
          /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Form.Field</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'submit'</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>This is the whole code to this point. Four fields, and all registered.</p>
<p>Now, on the Form, we need to make an <code>onSubmit</code> event. This means that if we click the Submit button at the bottom, our form data should be submitted.</p>
<pre><code>&lt;Form onSubmit={handleSubmit(onSubmit)}&gt;
</code></pre><p>And we also need to create a function onSubmit, that will do some specific action when the submit button is clicked or pressed.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> { register, handleSubmit, <span class="hljs-attr">formState</span>: { errors } } = useForm();
<span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(data);
}
</code></pre>
<p>So, if we click the submit button, our entered data will show up in the console.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/Screenshot-2021-10-09-104958.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-add-validation-to-our-forms">How to Add Validation to our Forms</h2>
<p>Now, here comes the final and most awaited step. Let's add the validations.</p>
<p>Let's start with the First Name field. We will use the required and maxLength properties, which are pretty self-explanatory. </p>
<ul>
<li><strong>Required</strong> means that the field is required.</li>
<li><strong>MaxLength</strong> denotes the maximum length of the characters we enter.</li>
</ul>
<pre><code class="lang-jsx">&lt;input
  placeholder=<span class="hljs-string">'First Name'</span>
  type=<span class="hljs-string">"text"</span>
  {...register(<span class="hljs-string">"firstName"</span>, { <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">maxLength</span>: <span class="hljs-number">10</span> })}
/&gt;
</code></pre>
<p>So, set <code>required</code> to true and <code>maxLength</code> to 10. Then if we submit the form without entering the First Name, or if the number of characters is more than 10, it will throw an error.</p>
<p>But we need to add the error message itself too. Add the following error message after the First Name form field.</p>
<pre><code>{errors.firstName &amp;&amp; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Please check the First Name<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>}
</code></pre><p>Here, it will throw an error. So, let's check what happened.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/Screenshot-2021-10-09-105958.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can see the error after the First Name field that says "Please check the First Name".</p>
<p>Repeat that process for Last Name.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/Screenshot-2021-10-09-110249.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Entering more than 10 characters will also throw an error.</p>
<p>Now, we need to add validation for the email and password fields. Here, we will use another property called <strong><code>Pattern</code></strong>. Pattern will contain a Regular Expression value, and it will be checked against the entered data in the form.</p>
<pre><code>pattern: <span class="hljs-regexp">/^(([^&lt;&gt;()\[\]\\.,;:\s@"]+(\.[^&lt;&gt;()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/</span>
</code></pre><p>This is what a Regular Expression pattern looks like. It's hard to read, but this is a pattern for Email Validation. Let's use this in our application.</p>
<pre><code class="lang-jsx">&lt;Form.Field&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Email<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span>
    <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'Email'</span>
    <span class="hljs-attr">type</span>=<span class="hljs-string">'email'</span>
    {<span class="hljs-attr">...register</span>('<span class="hljs-attr">email</span>', {
      <span class="hljs-attr">required:</span> <span class="hljs-attr">true</span>,
      <span class="hljs-attr">pattern:</span>
        /^(([^&lt;&gt;</span>()\[\]\\.,;:\s@"]+(\.[^<span class="hljs-tag">&lt;&gt;</span>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
    })}
  /&gt;</span>
&lt;/Form.Field&gt;
</code></pre>
<p>In the Email Form Field, add this pattern. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/Screenshot-2021-10-09-110849.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Entering the wrong email format will throw an error. But the error will disappear when we enter the right format.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/Screenshot-2021-10-09-110950.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Let's do the same for the Password Form Field. For the password field, we have the condition that it should contain one Capital Letter, one Small Letter, and the number of characters should be between 6 to 15. If our entered value fails any of these checks, it will throw an error.</p>
<pre><code class="lang-jsx">&lt;Form.Field&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Password<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span>
    <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'Password'</span>
    <span class="hljs-attr">type</span>=<span class="hljs-string">'password'</span>
    {<span class="hljs-attr">...register</span>('<span class="hljs-attr">password</span>', {
      <span class="hljs-attr">required:</span> <span class="hljs-attr">true</span>,
      <span class="hljs-attr">pattern:</span> /^(?=<span class="hljs-string">.*\d)(?</span>=<span class="hljs-string">.*[a-z])(?</span>=<span class="hljs-string">.*[A-Z]).{6,15}$/,</span>
    })}
  /&gt;</span></span>
&lt;/Form.Field&gt;
{
  errors.password &amp;&amp; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Please check the Password<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
}
</code></pre>
<p>Now, our all the four form fields are completed.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { Form, Button } <span class="hljs-keyword">from</span> <span class="hljs-string">'semantic-ui-react'</span>;
<span class="hljs-keyword">import</span> { useForm } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-hook-form'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">FormValidation</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> {
    register,
    handleSubmit,
    <span class="hljs-attr">formState</span>: { errors },
  } = useForm();
  <span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data);
  };
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit(onSubmit)}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Form.Field</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>First Name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'First Name'</span>
            <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
            {<span class="hljs-attr">...register</span>('<span class="hljs-attr">firstName</span>', { <span class="hljs-attr">required:</span> <span class="hljs-attr">true</span>, <span class="hljs-attr">maxLength:</span> <span class="hljs-attr">10</span> })}
          /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Form.Field</span>&gt;</span>
        {errors.firstName &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Please check the First Name<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
        <span class="hljs-tag">&lt;<span class="hljs-name">Form.Field</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Last Name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'Last Name'</span>
            <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
            {<span class="hljs-attr">...register</span>('<span class="hljs-attr">lastName</span>', { <span class="hljs-attr">required:</span> <span class="hljs-attr">true</span>, <span class="hljs-attr">maxLength:</span> <span class="hljs-attr">10</span> })}
          /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Form.Field</span>&gt;</span>
        {errors.lastName &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Please check the Last Name<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
        <span class="hljs-tag">&lt;<span class="hljs-name">Form.Field</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Email<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'Email'</span>
            <span class="hljs-attr">type</span>=<span class="hljs-string">'email'</span>
            {<span class="hljs-attr">...register</span>('<span class="hljs-attr">email</span>', {
              <span class="hljs-attr">required:</span> <span class="hljs-attr">true</span>,
              <span class="hljs-attr">pattern:</span>
                /^(([^&lt;&gt;</span>()\[\]\\.,;:\s@"]+(\.[^<span class="hljs-tag">&lt;&gt;</span>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
            })}
          /&gt;
        <span class="hljs-tag">&lt;/<span class="hljs-name">Form.Field</span>&gt;</span>
        {errors.email &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Please check the Email<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
        <span class="hljs-tag">&lt;<span class="hljs-name">Form.Field</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Password<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'Password'</span>
            <span class="hljs-attr">type</span>=<span class="hljs-string">'password'</span>
            {<span class="hljs-attr">...register</span>('<span class="hljs-attr">password</span>', {
              <span class="hljs-attr">required:</span> <span class="hljs-attr">true</span>,
              <span class="hljs-attr">pattern:</span> /^(?=<span class="hljs-string">.*\d)(?</span>=<span class="hljs-string">.*[a-z])(?</span>=<span class="hljs-string">.*[A-Z]).{6,15}$/,</span>
            })}
          /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Form.Field</span>&gt;</span>
        {errors.password &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Please check the Password<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
        <span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'submit'</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Here's the whole code for your reference. And we can also add some styling to our error messages – something like this, maybe:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/Screenshot-2021-10-09-111533.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Now you know how to add validation in React Forms. Note that React Hook Form only works in Functional Components, not in Class Components.</p>
<p>You can check out my video on <a target="_blank" href="https://www.youtube.com/watch?v=7Jc5t9XEQIg&amp;t=904s&amp;ab_channel=Cybernatico">Let's add Validation in Forms using React and React Hook Form</a>, which is on my YouTube channel.</p>
<p>And here's the whole code on <a target="_blank" href="https://github.com/nishant-666/React-Form-Validation-">GitHub</a> for your reference.</p>
<blockquote>
<p>Happy Learning.</p>
</blockquote>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn JavaScript Form Validation – Build a JS Project for Beginners ✨ ]]>
                </title>
                <description>
                    <![CDATA[ Today we're going to learn how to do form validation in JavaScript. We'l also add images and media queries to build out the entire project and keep it as a portfolio.   Here's the project demo that we're gonna build 👇 Desktop design Here's a small ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-javascript-form-validation-by-making-a-form/</link>
                <guid isPermaLink="false">66b209694b36d956a7749c20</guid>
                
                    <category>
                        <![CDATA[ Form validations ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joy Shaheb ]]>
                </dc:creator>
                <pubDate>Wed, 22 Sep 2021 18:33:54 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/09/Frame-31.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Today we're going to learn how to do <strong>form validation</strong> in JavaScript. We'l also add images and media queries to build out the entire project and keep it as a <strong>portfolio</strong>.  </p>
<p>Here's the project demo that we're gonna build 👇</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Frame-30--1-.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Desktop design</strong></em></p>
<p>Here's a small sample of how the form will work 👇</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/dvdfvdf-1.gif" alt="Image" width="600" height="400" loading="lazy">
<em><strong>project sample</strong></em></p>
<h2 id="heading-you-can-watch-this-tutorial-on-youtube-as-well-if-you-like"><strong>You can watch this tutorial on YouTube as well if you like:</strong></h2>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/VufN46OyFng" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-source-code">Source code</h2>
<p>You can get the source code, including the images, from here:</p>
<ul>
<li><a target="_blank" href="https://codepen.io/joyshaheb/pen/XWgdOyY">CodePen</a></li>
<li><a target="_blank" href="https://github.com/JoyShaheb/Project-image-repo/tree/main/Form-Validation">GitHub</a></li>
</ul>
<h1 id="heading-how-to-setup-the-project">How to Setup the Project</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Frame-1--1-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Follow these steps to set up our project: 👇</p>
<ul>
<li>Create a new folder named "Project" and open VS Code</li>
<li>Create index.html, style.css, and main.js files</li>
<li>Link the files inside the HTML </li>
<li>Download the <a target="_blank" href="https://github.com/JoyShaheb/Project-image-repo/tree/main/Form-Validation">images from my GitHub repository</a></li>
<li>Paste this font-awesome link inside the head tag. Then, we can access Font Awesome icons 👇👇</li>
</ul>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">link</span>
      <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>
      <span class="hljs-attr">href</span>=<span class="hljs-string">"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"</span>
      <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>
    /&gt;</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Frame-2--1-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h1 id="heading-heres-what-well-cover">Here's what we'll cover:</h1>
<ul>
<li>Writing the HTML</li>
<li>Adding the CSS</li>
<li>Writing the JavaScript</li>
<li>Adding a social media button</li>
<li>Adding the images</li>
<li>Media queries for the mobile version (responsive)</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Frame-20--2-.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Table of contents</strong></em></p>
<h1 id="heading-how-to-write-the-html">How to Write the HTML</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Frame-3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Create a class named <code>.container</code> inside the body tag and host the form tag which will have an id of form 👇</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"form"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>And inside the form tag, create 4 <code>div</code>s, like this 👇</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"form"</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"title"</span>&gt;</span>Get Started<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>Inside those 3 empty div tags, let's create 3 inputs [Username, Email, and Password] along with the icons and labels.</p>
<p><strong>Note</strong>: we are creating an <code>.error</code> class name. We will inject the error message here using JavaScript. </p>
<h4 id="heading-username-input">Username Input</h4>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- User Name input --&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"username"</span>&gt;</span>User Name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fas fa-user"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
        <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span>
        <span class="hljs-attr">id</span>=<span class="hljs-string">"username"</span>
        <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Joy Shaheb"</span>
     /&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fas fa-exclamation-circle failure-icon"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"far fa-check-circle success-icon"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"error"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h4 id="heading-email-input">Email Input</h4>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- Email input --&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"email"</span>&gt;</span>Email<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"far fa-envelope"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span>
        <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span>
        <span class="hljs-attr">id</span>=<span class="hljs-string">"email"</span>
        <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"abc@gmail.com"</span>
     /&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fas fa-exclamation-circle failure-icon"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"far fa-check-circle success-icon"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"error"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h4 id="heading-password-input">Password Input</h4>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!--   Password input --&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"password"</span>&gt;</span>Password<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fas fa-lock"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span>
        <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span>
        <span class="hljs-attr">id</span>=<span class="hljs-string">"password"</span>
        <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password here"</span>
     /&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fas fa-exclamation-circle failure-icon"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"far fa-check-circle success-icon"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"error"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h4 id="heading-how-to-make-the-button">How to make the button</h4>
<p>Finally, add the button before the form closing tag like this:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- other codes are here --&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>Here's the result so far 👇</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/fdgdfgdfdffcvb.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Result So far</strong></em></p>
<p>Congrats on completing the HTML part! 🍾🎉🥂</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Frame-7.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h1 id="heading-how-to-add-the-css">How to Add the CSS</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Frame-4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Let's add the CSS to style our form. First, let's remove the default styles of our browser including the font-family👇</p>
<pre><code class="lang-css"><span class="hljs-comment">/**
* ! changing default styles of brower
**/</span>

* {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">box-sizing</span>: border-box;
}

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">font-family</span>: sans-serif;
}
</code></pre>
<p>Now, apply these styles for the form tag:</p>
<pre><code class="lang-css"><span class="hljs-comment">/**
* ! style rules for form section
**/</span>

<span class="hljs-selector-tag">form</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">max-width</span>: <span class="hljs-number">400px</span>;
  <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">2px</span> <span class="hljs-number">2px</span> <span class="hljs-number">4px</span> <span class="hljs-built_in">rgba</span>(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0.1</span>);
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">50px</span>;
}
</code></pre>
<p>Next, make these changes for our title text: 👇👇</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.title</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">font-weight</span>: bold;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
}
</code></pre>
<p>Your result so far 👇👇</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/fsdfsdsfxvxcvxd.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Result so far</strong></em></p>
<p>Now, add a margin to the bottom of our label text like this:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">label</span> {
  <span class="hljs-attribute">display</span>: block;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">5px</span>;
}
</code></pre>
<p>And add these styles to change the look and feel of our input tags 👇👇</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">form</span> <span class="hljs-selector-tag">div</span> <span class="hljs-selector-tag">input</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">40px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">8px</span>;
  <span class="hljs-attribute">outline</span>: none;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid <span class="hljs-number">#c4c4c4</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span> <span class="hljs-number">30px</span>;
  <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">2px</span> <span class="hljs-number">2px</span> <span class="hljs-number">4px</span> <span class="hljs-built_in">rgba</span>(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0.1</span>);
}
</code></pre>
<p>Add this code to add some space and color changing effects:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">form</span> <span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">position</span>: relative;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">15px</span>;
}

<span class="hljs-selector-tag">input</span><span class="hljs-selector-pseudo">:focus</span> {
  <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid <span class="hljs-number">#f2796e</span>;
}
</code></pre>
<p>The result so far 👇👇</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/fdfdfdfdfvdfv.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Result so far</strong></em></p>
<h2 id="heading-how-to-style-the-icons">How to Style the Icons</h2>
<p>Now we're gonna style the icons which we imported from font-awesome. Follow along with the code: ✨✨</p>
<pre><code class="lang-css"><span class="hljs-comment">/**
* ! style rules for form icons
**/</span>

<span class="hljs-selector-tag">form</span> <span class="hljs-selector-tag">div</span> <span class="hljs-selector-tag">i</span> {
  <span class="hljs-attribute">position</span>: absolute;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p>Here's the result of adding those two lines 👇👇</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/fddfvdfvdfvgfbh.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Result so far</strong></em></p>
<p>Now, add these styles to style the error class, along with the success and failure icons 👇👇</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.failure-icon</span>,
<span class="hljs-selector-class">.error</span> {
  <span class="hljs-attribute">color</span>: red;
}

<span class="hljs-selector-class">.success-icon</span> {
  <span class="hljs-attribute">color</span>: green;
}

<span class="hljs-selector-class">.error</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">14.5px</span>;
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">5px</span>;
}
</code></pre>
<p>Here's the result so far 👇👇</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/ddsfsddsdscsfvv.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Result so far</strong></em></p>
<p>Look, the success and failure icons are overlapping each other. Don't worry, we will manipulate those in JavaScript. For now, you can hide them like this👇👇</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.success-icon</span>,
<span class="hljs-selector-class">.failure-icon</span> {
  <span class="hljs-attribute">right</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">opacity</span>: <span class="hljs-number">0</span>;
}
</code></pre>
<p>Now, let's style our submit button, like this 👇</p>
<pre><code class="lang-css"><span class="hljs-comment">/* Style rules for submit btn */</span>

<span class="hljs-selector-tag">button</span> {
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">15px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">45px</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f2796e</span>;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid <span class="hljs-number">#f2796e</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">8px</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">cursor</span>: pointer;
  <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">2px</span> <span class="hljs-number">2px</span> <span class="hljs-number">4px</span> <span class="hljs-built_in">rgba</span>(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0.1</span>);
  <span class="hljs-attribute">transition</span>: all <span class="hljs-number">0.1s</span> ease;
}
</code></pre>
<p>If you want to add a hover effect, then sure, add these styles 👇👇</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">button</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">opacity</span>: <span class="hljs-number">0.8</span>;
}
</code></pre>
<h1 id="heading-take-a-break">Take a Break!</h1>
<p>So far so good. Take a break – you deserve it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Frame-33.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h1 id="heading-how-to-add-the-javascript">How to Add the JavaScript</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Frame-6.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>First, we need to target all our classes and id from the HTML inside the JavaScript. To do this task efficiently, make these two functions 👇👇</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">let</span> <span class="hljs-selector-tag">id</span> = (<span class="hljs-selector-tag">id</span>) =&gt; <span class="hljs-selector-tag">document</span><span class="hljs-selector-class">.getElementById</span>(<span class="hljs-selector-tag">id</span>);

<span class="hljs-selector-tag">let</span> <span class="hljs-selector-tag">classes</span> = (<span class="hljs-selector-tag">classes</span>) =&gt; <span class="hljs-selector-tag">document</span><span class="hljs-selector-class">.getElementsByClassName</span>(<span class="hljs-selector-tag">classes</span>);
</code></pre>
<p>Then, store the classes and id inside these variables 👇</p>
<p><strong>Note:</strong> Try not to make spelling mistakes. Otherwise, your JavaScript will not work.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> username = id(<span class="hljs-string">"username"</span>),
  email = id(<span class="hljs-string">"email"</span>),
  password = id(<span class="hljs-string">"password"</span>),
  form = id(<span class="hljs-string">"form"</span>),

  errorMsg = classes(<span class="hljs-string">"error"</span>),
  successIcon = classes(<span class="hljs-string">"success-icon"</span>),
  failureIcon = classes(<span class="hljs-string">"failure-icon"</span>);
</code></pre>
<p>Now, we're gonna target our form and add the <strong>submit</strong> event listener 👇 </p>
<pre><code class="lang-css">
<span class="hljs-selector-tag">form</span><span class="hljs-selector-class">.addEventListener</span>("<span class="hljs-selector-tag">submit</span>", (<span class="hljs-selector-tag">e</span>) =&gt; {
  e.preventDefault();
});
</code></pre>
<p>Now, we will create a function named engine which will do all sorts of form validation work for us. It will have three arguments – follow along here: 👇</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> engine = <span class="hljs-function">(<span class="hljs-params">id, serial, message</span>) =&gt;</span> {}
</code></pre>
<p>The arguments represent the following:</p>
<ul>
<li><code>id</code> will target our id</li>
<li><code>serial</code> will target our classes [error class, success and failure icons]</li>
<li><code>message</code> will print a message inside our .error class </li>
</ul>
<p>Now create an <code>if, else</code> statement like this 👇</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> engine = <span class="hljs-function">(<span class="hljs-params">id, serial, message</span>) =&gt;</span> {

  <span class="hljs-keyword">if</span> (id.value.trim() === <span class="hljs-string">""</span>) {
  } 

  <span class="hljs-keyword">else</span> {
  }
}
</code></pre>
<p><strong>Note:</strong> the <strong><code>id.value.trim()</code></strong> will remove all the extra white spaces from the value which the user inputs. You can get an idea of how it works by looking at this illustration 👇</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Frame-19-1.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>trim() used to remove extra spaces</strong></em></p>
<p>Now, look at our objectives 👇</p>
<ul>
<li>We want the JavaScript to print a message inside the <strong>error</strong> class whenever the user <strong>submits a blank</strong> <strong>form</strong>. At the same time, we want the <strong>failure</strong> icons to highlight as well. </li>
<li>But, if the user <strong>fills in all the inputs</strong> and submits it, we want the <strong>success</strong> icon to be visible.</li>
</ul>
<p>To accomplish this, write this logic 👇 to print the message:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> engine = <span class="hljs-function">(<span class="hljs-params">id, serial, message</span>) =&gt;</span> {

  <span class="hljs-keyword">if</span> (id.value.trim() === <span class="hljs-string">""</span>) {
    errorMsg[serial].innerHTML = message;
  } 

  <span class="hljs-keyword">else</span> {
    errorMsg[serial].innerHTML = <span class="hljs-string">""</span>;
  }
}
</code></pre>
<p>For the icons to work properly, add this code: 👇👇</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> engine = <span class="hljs-function">(<span class="hljs-params">id, serial, message</span>) =&gt;</span> {

  <span class="hljs-keyword">if</span> (id.value.trim() === <span class="hljs-string">""</span>) {
    errorMsg[serial].innerHTML = message;
    id.style.border = <span class="hljs-string">"2px solid red"</span>;

    <span class="hljs-comment">// icons</span>
    failureIcon[serial].style.opacity = <span class="hljs-string">"1"</span>;
    successIcon[serial].style.opacity = <span class="hljs-string">"0"</span>;
  } 

  <span class="hljs-keyword">else</span> {
    errorMsg[serial].innerHTML = <span class="hljs-string">""</span>;
    id.style.border = <span class="hljs-string">"2px solid green"</span>;

    <span class="hljs-comment">// icons</span>
    failureIcon[serial].style.opacity = <span class="hljs-string">"0"</span>;
    successIcon[serial].style.opacity = <span class="hljs-string">"1"</span>;
  }
}
</code></pre>
<p>Time to implement our newly created function. Write these inside the place where we added the submit event listener 👇</p>
<pre><code class="lang-js">form.addEventListener(<span class="hljs-string">"submit"</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  e.preventDefault();

  engine(username, <span class="hljs-number">0</span>, <span class="hljs-string">"Username cannot be blank"</span>);
  engine(email, <span class="hljs-number">1</span>, <span class="hljs-string">"Email cannot be blank"</span>);
  engine(password, <span class="hljs-number">2</span>, <span class="hljs-string">"Password cannot be blank"</span>);
});
</code></pre>
<p>Here, we are passing the id names, serials of our class names, and passing the message which should be printed when we find an error when the user submits the form. </p>
<p>Here are the results so far 👇</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/dvdfvdf.gif" alt="Image" width="600" height="400" loading="lazy">
<em><strong>The Result so far</strong></em></p>
<h2 id="heading-how-to-add-the-social-media-buttons">How to Add the Social Media Buttons</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Frame-10.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>So far so good, let's add social media sign up options. Follow along here. 👇 </p>
<p>Inside the form tag, create a new <code>div</code> with the class name <code>social</code>:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"form"</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"social"</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"title"</span>&gt;</span>Get Started<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"question"</span>&gt;</span>
        Already Have an Account? <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Sign In<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"or"</span>&gt;</span>Or<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    <span class="hljs-comment">&lt;!-- other codes are here--&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>Inside the <code>.btn</code> class, we create two more divs with class names <code>.btn-1</code> and <code>.btn-2</code> with the images and text as well</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn-1"</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://img.icons8.com/color/30/000000/google-logo.png"</span> /&gt;</span>
     Sign Up
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn-2"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://img.icons8.com/ios-filled/30/ffffff/facebook-new.png"</span> /&gt;</span>
     Sign Up
   <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>Here are the results so far 👇👇</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/dfvgdfdsfdsf.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>The Result so far</strong></em></p>
<p>Now, let's style the <code>.btn-1</code> and <code>.btn-2</code> first. We'll change the alignment of the buttons to row from column 👇</p>
<pre><code class="lang-css"><span class="hljs-comment">/**
* ! style rules for social section
**/</span>

<span class="hljs-selector-class">.btn</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: row;
  <span class="hljs-attribute">justify-content</span>: space-between;
  <span class="hljs-attribute">gap</span>: <span class="hljs-number">15px</span>;
}
</code></pre>
<p>Here's what it looks like now:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/dfdfdfdbgf.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>The Result so far</strong></em></p>
<p>Now, add styles for the button like this: 👇</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.btn-1</span>,
<span class="hljs-selector-class">.btn-2</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">5px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">gap</span>: <span class="hljs-number">15px</span>;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid <span class="hljs-number">#c4c4c4</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">8px</span>;
  <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">2px</span> <span class="hljs-number">2px</span> <span class="hljs-number">4px</span> <span class="hljs-built_in">rgba</span>(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0.1</span>);
  <span class="hljs-attribute">cursor</span>: pointer;
}
</code></pre>
<p>Change the icon color and text color of <code>.btn-2</code> like this: 👇</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.btn-2</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#4f70b5</span>;
  <span class="hljs-attribute">color</span>: white;
}
</code></pre>
<p>Then add these small changes to make the component look better:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.or</span> {
  <span class="hljs-attribute">text-align</span>: center;
}

<span class="hljs-selector-class">.question</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">15px</span>;
}

<span class="hljs-selector-tag">span</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#f2796e</span>;
  <span class="hljs-attribute">cursor</span>: pointer;
}
</code></pre>
<p>The result so far:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/fdfhgnmhg.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Result so far</strong></em></p>
<h2 id="heading-how-to-add-the-images">How to Add the Images</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Frame-9.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now, let's add images to our project. First, let's write the HTML 👇</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"content"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"logo"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://svgshare.com/i/_go.svg"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"image"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text"</span>&gt;</span>
          Start for free &amp; get <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
          attractive offers today !
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>  
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

   <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"form"</span>&gt;</span>
   <span class="hljs-comment">&lt;!--other codes are here --&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>The result so far 👇</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/dfghgjgjgytfh.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Result so far</strong></em></p>
<p>Now we need to change the orientation of our content from column to row. Follow along 👇</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: row;
}
</code></pre>
<p>Add these style rules for the content section:</p>
<pre><code class="lang-css"><span class="hljs-comment">/**
* ! style rules for content section
**/</span>

<span class="hljs-selector-class">.content</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">justify-content</span>: space-around;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f2796e</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">55%</span>;
  <span class="hljs-attribute">min-height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-tag">form</span> {
   <span class="hljs-attribute">width</span>: <span class="hljs-number">45%</span>;
   <span class="hljs-attribute">max-width</span>: none;
}
</code></pre>
<p>The result so far 👇</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/dsffgythjy.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Result so far</strong></em></p>
<p>Add the main illustration in CSS:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.image</span> {
  <span class="hljs-attribute">background-image</span>: <span class="hljs-built_in">url</span>(<span class="hljs-string">"https://svgshare.com/i/_gZ.svg"</span>);
  <span class="hljs-attribute">background-repeat</span>: no-repeat;
  <span class="hljs-attribute">background-size</span>: contain;
  <span class="hljs-attribute">background-position</span>: center;
  <span class="hljs-comment">/* border: 2px solid black; */</span>
  <span class="hljs-attribute">height</span>: <span class="hljs-number">65%</span>;
}
</code></pre>
<p>And add these styles for the <code>.text</code> class:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.text</span> {
  <span class="hljs-attribute">text-align</span>: center;
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
}

<span class="hljs-selector-tag">form</span> {
   <span class="hljs-attribute">width</span>: <span class="hljs-number">45%</span>;
   <span class="hljs-attribute">max-width</span>: none;
}
</code></pre>
<p>The result so far 👇</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/wewrwerew.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Result so far</strong></em></p>
<h2 id="heading-how-to-add-media-queries-for-the-mobile-version">How to Add Media Queries for the Mobile Version</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Frame-8.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We want to make this responsive. So we'll add media queries to help us with that.</p>
<p>For screens with a width from 900px, we will add these styles. Follow along 👇👇</p>
<pre><code class="lang-css"><span class="hljs-keyword">@media</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">900px</span>) {
  <span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">flex-direction</span>: column;
  }

  <span class="hljs-selector-tag">form</span>,
  <span class="hljs-selector-class">.content</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  }

  <span class="hljs-selector-class">.btn</span> {
    <span class="hljs-attribute">flex-direction</span>: column;
  }
  <span class="hljs-selector-class">.image</span> {
    <span class="hljs-attribute">height</span>: <span class="hljs-number">70vh</span>;
  }
}
</code></pre>
<p>For screens with a width from 425px, we will make these minor changes 👇</p>
<pre><code class="lang-css"><span class="hljs-keyword">@media</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">425px</span>) {
  <span class="hljs-selector-tag">form</span> {
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
  }
}
</code></pre>
<p>Here's the final result 👇👇</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/fgbgfnghnghnhgmjhgnmhgnhgnggfbgfgfb.gif" alt="Image" width="600" height="400" loading="lazy">
<em><strong>The final result</strong></em></p>
<h1 id="heading-conclusion">Conclusion</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Frame-5.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Congratulations !</strong></em></p>
<p>Congratulations for reading until the end. Now you can easily and efficiently use JavaScript to handle form validation. Not only that, <strong>you also have a project to show your local recruiter!</strong></p>
<p>Here's your medal for reading till the end ❤️</p>
<h3 id="heading-suggestions-amp-criticisms-are-highly-appreciated">Suggestions &amp; Criticisms Are Highly Appreciated ❤️</h3>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/usxsz1lstuwry3jlly4d.png" alt="Alt Text" width="1000" height="245" loading="lazy"></p>
<ul>
<li><a target="_blank" href="https://www.linkedin.com/in/joyshaheb/"><strong>LinkedIn/ JoyShaheb</strong></a></li>
<li><strong><a target="_blank" href="https://www.youtube.com/c/joyshaheb">YouTube / JoyShaheb</a></strong></li>
<li><strong><a target="_blank" href="https://twitter.com/JoyShaheb">Twitter / JoyShaheb</a></strong></li>
<li><strong><a target="_blank" href="https://www.instagram.com/joyshaheb/">Instagram/ JoyShaheb</a></strong></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Chakra UI and React-Hook-Form –How to Build Beautiful Forms ]]>
                </title>
                <description>
                    <![CDATA[ In HTML, it’s the default behavior for forms to redirect to a new page whenever they're submitted. So in order to provide dynamic functionality, React uses a strategy called controlled components. If you have recently gone through a React course, you... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-react-hook-form-with-chakra-ui/</link>
                <guid isPermaLink="false">66ba6090bca875d7790d6aa3</guid>
                
                    <category>
                        <![CDATA[ Form validations ]]>
                    </category>
                
                    <category>
                        <![CDATA[ forms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Georgey V B ]]>
                </dc:creator>
                <pubDate>Tue, 25 May 2021 20:26:38 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/05/Blog-7-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In HTML, it’s the default behavior for forms to redirect to a new page whenever they're submitted. So in order to provide dynamic functionality, React uses a strategy called <strong>controlled components</strong>.</p>
<p>If you have recently gone through a React course, you probably didn't like this part, because there are a lot of states to manage if you have multiple input fields.</p>
<p>Firstly, you track the state of the input field using the <code>onChange</code> property which calls the <code>useState()</code> function. The input fields are wrapped around a form element. </p>
<p>When the user submits the form, it triggers the <code>onClick</code> or <code>onSubmit</code> property to set the inputs either to an array containing values or objects, depending on the number of input fields.</p>
<p>Then comes validation, which checks whether the user has entered any input. If not, then return an error, prompting the user to enter a valid input. </p>
<p>The logic here is a whole lot of boilerplate. You might be bored just hearing about the process.</p>
<p>What if I tell you that a single library can achieve all of this?</p>
<p>Here is what I’ll cover in this article:</p>
<ol>
<li>What is React-Hook-Form?</li>
<li>How React-Hook-Form Affects Performance</li>
<li>How to Get User Data</li>
<li>How to Add Validation to Your Forms</li>
<li>How to Improve the Front End and User Experience Using Chakra-UI.</li>
</ol>
<h2 id="heading-what-is-react-hook-form">What is React-Hook-Form?</h2>
<p>React-Hook-Form is a flexible library that takes care of all your validation, state management, and user data – and it's all packed within a size of 25.3 kb (unpacked) and 9.1 kb GZip (changes with versions). </p>
<p>It's simple and straightforward to use, and you have to write minimal code.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/bundle-size.png" alt="Bundle size by bundlephobia.com" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://bundlephobia.com/result?p=react-hook-form@7.6.0">Image source</a></em></p>
<p>One of the features I’m impressed with is its performance. As mentioned in its <a target="_blank" href="https://react-hook-form.com/">official site</a>, React-Hook-Form:</p>
<p><em>“Minimizes the number of re-renders and faster mounting, striving to provide the best user experience.”</em></p>
<h2 id="heading-how-react-hook-form-affects-performance">How React-Hook-Form Affects Performance</h2>
<p>If you have been following the previous versions of the library, the documentation often referenced the <code>ref</code> property to handle state management and validation.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">”password”</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">”Password”</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{register}</span> /&gt;</span>
</code></pre>
<p>In this way, React-Hook-Form adopts a method of <strong>uncontrolled</strong> input, rather than changing the state every single time. It isolates the selected component and avoids rendering the child components. </p>
<p>This significantly reduces the number of re-renders and boosts the overall performance of the application. (<a target="_blank" href="https://blog.logrocket.com/the-complete-guide-to-react-hook-form/#:~:text=React%20Hook%20Form%20adopts%20the,and%20it%20has%20zero%20dependencies.">Source</a>)</p>
<h2 id="heading-how-to-get-user-data-from-a-form">How to Get User Data from a Form</h2>
<p>I have made a Codesandbox for this particular tutorial, so make sure you refer to it in case you get lost.</p>
<p>Here's what you'll need to follow along:</p>
<ul>
<li><a target="_blank" href="https://cn7hq.csb.app/">App link</a></li>
<li><a target="_blank" href="https://codesandbox.io/s/funny-cartwright-cn7hq?file=/src/index.js">Source code</a></li>
</ul>
<p>And here’s what we will be building. It's a simple form with validation, alerts when a user submits, and errors that's built using Chakra UI.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/demo.png" alt="Demo of what we will be building" width="600" height="400" loading="lazy"></p>
<p>First, let's install the library:</p>
<pre><code class="lang-bash">npm install react-hook-form
</code></pre>
<p>Now import the <code>useForm</code> hook from the package:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useForm } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-hook-form"</span>;
</code></pre>
<p>Destructure the following constants from the <code>useForm</code> hook:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { register, handleSubmit, <span class="hljs-attr">formState</span>: { errors } } = useForm();
</code></pre>
<p>Create a simple form element like this:</p>
<pre><code class="lang-js">&lt;form onSubmit={handleSubmit(onSubmit)}&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">”text”</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">”First</span> <span class="hljs-attr">Name</span>” {<span class="hljs-attr">...register</span>(“<span class="hljs-attr">firstname</span>”)} /&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">”submit”</span> /&gt;</span></span>
&lt;/form&gt;
</code></pre>
<p>On submit, the form will pass a function onto the handleSubmit function. We can define the <code>onSubmit</code> function like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data);
</code></pre>
<p>Now if we test out our form element, when it's submitted the console returns the following:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/log-2.png" alt="Codesandbox console log preview" width="600" height="400" loading="lazy"></p>
<p>Looks like it returned an object with the property <code>firstname</code> and has successfully gotten ahold of the data in the input field.</p>
<p>Let’s now add a bunch more input fields: </p>
<pre><code class="lang-js">&lt;form onSubmit={handleSubmit(onSubmit)}&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">”text”</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">”First</span> <span class="hljs-attr">Name</span>” {<span class="hljs-attr">...register</span>(“<span class="hljs-attr">firstname</span>”)} /&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">”text”</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">”Last</span> <span class="hljs-attr">Name</span>” {<span class="hljs-attr">...register</span>(“<span class="hljs-attr">lastname</span>”)} /&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">”password”</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">”Your</span> <span class="hljs-attr">password</span>” {<span class="hljs-attr">...register</span>(“<span class="hljs-attr">password</span>”)} /&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">”submit”</span> /&gt;</span></span>
&lt;/form&gt;
</code></pre>
<p>On logging the response, we get an object back:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/Surface-Pro-3---1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now, this data can be sent back to the database. But in this tutorial, let’s just display it back to the user, using <code>useState( )</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [data, setData] = useState();
<span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
   setData(data);
 };
</code></pre>
<p>Let’s make a new component called <code>Stats.js</code>. Here, we’ll make use of Chakra UI’s <code>Stat</code> component. </p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> {
 HStack,
 Stack,
 Stat,
 StatHelpText,
 StatLabel
} <span class="hljs-keyword">from</span> <span class="hljs-string">"@chakra-ui/react"</span>;
<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Stats</span>(<span class="hljs-params">props</span>) </span>{
 <span class="hljs-keyword">return</span> (
   <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Stat</span> <span class="hljs-attr">mt</span>=<span class="hljs-string">{5}</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">Stack</span>
       <span class="hljs-attr">p</span>=<span class="hljs-string">{4}</span>
       <span class="hljs-attr">borderWidth</span>=<span class="hljs-string">"3px"</span>
       <span class="hljs-attr">borderRadius</span>=<span class="hljs-string">"md"</span>
       <span class="hljs-attr">direction</span>=<span class="hljs-string">"column"</span>
       <span class="hljs-attr">align</span>=<span class="hljs-string">"flex-start"</span>
     &gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">HStack</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">StatLabel</span>&gt;</span>Name: {props.Firstname}<span class="hljs-tag">&lt;/<span class="hljs-name">StatLabel</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">StatLabel</span>&gt;</span>{props.Lastname}<span class="hljs-tag">&lt;/<span class="hljs-name">StatLabel</span>&gt;</span>
       <span class="hljs-tag">&lt;/<span class="hljs-name">HStack</span>&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">StatHelpText</span>&gt;</span>Password: {props.Password}<span class="hljs-tag">&lt;/<span class="hljs-name">StatHelpText</span>&gt;</span>
     <span class="hljs-tag">&lt;/<span class="hljs-name">Stack</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">Stat</span>&gt;</span></span>
 );
}
</code></pre>
<p>Now, import this component into your root file and pass the respective props.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> Stats <span class="hljs-keyword">from</span> <span class="hljs-string">"./Stats"</span>;
<span class="hljs-comment">// App.js</span>
{data &amp;&amp; (
       <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Stats</span>
         <span class="hljs-attr">Firstname</span>=<span class="hljs-string">{data.firstname}</span>
         <span class="hljs-attr">Lastname</span>=<span class="hljs-string">{data.lastname}</span>
         <span class="hljs-attr">Password</span>=<span class="hljs-string">{data.password}</span>
       /&gt;</span></span>
)}
</code></pre>
<p>The stats will only be displayed if the data is <code>true</code>.</p>
<p>The final result should look something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/Surface-Pro-4---1.png" alt="Result displayed to front-end" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-add-validation-to-a-form">How to Add Validation to a Form</h2>
<p>Why do we need validation anyways? Let me take you through an example I went through during one of the hackathon projects I was working on. </p>
<p>I had built a Password manager, and I didn’t pay any attention to form validation. Users started entering empty passwords into the form. Eventually, there was a whole load of invalid data in the database.</p>
<p>Now if you visit any popular site, you might have noticed that it forces you to enter a strong password.</p>
<p>Let’s draw some conclusions from this case-study</p>
<ul>
<li>We want to get valid data</li>
<li>We want our user data to be protected by entering strong passwords</li>
<li>We want to keep the database clean by blocking invalid data</li>
</ul>
<p>We’ll try to achieve these objectives using client-side validation provided by React-Hook-Form. We will use the <code>register</code> method provided by the library. It allows you to register the data a user enters and apply validation rules to it.</p>
<p>Consider the example below: </p>
<pre><code class="lang-js">&lt;input
      type=<span class="hljs-string">"text"</span>
      placeholder=<span class="hljs-string">"First name"</span>
      {...register(<span class="hljs-string">"firstname"</span>, { <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span> })}
/&gt;


By setting the rule required to <span class="hljs-string">`true`</span>, the user will be now forced to provide a string to pass the validation. We can further modify <span class="hljs-built_in">this</span> by returning a message back to the user when <span class="hljs-built_in">this</span> event occurs.

<span class="hljs-string">``</span><span class="hljs-string">`js
&lt;input
      type="text"
      placeholder="First name"
      {...register("firstname", { required: “Please enter your first name” })}
/&gt;
{errors.firstname &amp;&amp; &lt;p&gt;{errors.firstname.message}&lt;/p&gt;}</span>
</code></pre>
<p>If the object <code>errors</code> returns a true value, it will display the message to the user.</p>
<p>Let’s now force the user to provide a password with more than 8 characters. </p>
<pre><code class="lang-js">&lt;Input
      type=<span class="hljs-string">"password"</span>
      placeholder=<span class="hljs-string">"Password"</span>
      {...register(<span class="hljs-string">"password"</span>, {
        <span class="hljs-attr">required</span>: <span class="hljs-string">"Please enter Password"</span>,
        <span class="hljs-attr">minLength</span>: { <span class="hljs-attr">value</span>: <span class="hljs-number">8</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">"Too short"</span> }
      })}
 /&gt;
</code></pre>
<p>By assigning the minLength property to 8, the user now will be compelled to enter an 8 character password.</p>
<p>Also, we can alert the user at the front-end by using the same method we used previously using <code>And operator</code>.</p>
<pre><code class="lang-js">{errors.password &amp;&amp; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{errors.password.message}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>}
</code></pre>
<p>If you notice now, React-Hook-Form listens to the changes dynamically. So if the input is left empty, it displays an alert at the same time. If the password is too short, it updates the message dynamically. Beauty!</p>
<p>Now go ahead and make your own form. In the next section we’ll customise the form and send alerts to the user when an error pops up.</p>
<h2 id="heading-how-to-improve-the-front-end-and-user-experience-using-chakra-ui">How to Improve the Front End and User Experience Using Chakra-UI</h2>
<p>First of all let’s convert all the components we've used so far to Chakra UI components.</p>
<p>Instead of the normal <code>&lt;input /&gt;</code>, simply replace the existing one with the <code>Input</code> from Chakra UI. </p>
<pre><code class="lang-js">Import { Input } <span class="hljs-keyword">from</span> “@chakra-ui/react”
</code></pre>
<p>Now import the <code>VStack</code> and <code>Button</code> component the same way and wrap the whole form with <code>VStack</code>.</p>
<pre><code class="lang-js">&lt;VStack&gt;
         <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Input</span>
           <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
           <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"First name"</span>
           {<span class="hljs-attr">...register</span>("<span class="hljs-attr">firstname</span>", {
             <span class="hljs-attr">required:</span> "<span class="hljs-attr">Please</span> <span class="hljs-attr">enter</span> <span class="hljs-attr">first</span> <span class="hljs-attr">name</span>",
             <span class="hljs-attr">minLength:</span> <span class="hljs-attr">3</span>,
             <span class="hljs-attr">maxLength:</span> <span class="hljs-attr">80</span>
           })}
         /&gt;</span></span>
         <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Input</span>
           <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
           <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Last name"</span>
           {<span class="hljs-attr">...register</span>("<span class="hljs-attr">lastname</span>", {
             <span class="hljs-attr">required:</span> "<span class="hljs-attr">Please</span> <span class="hljs-attr">enter</span> <span class="hljs-attr">Last</span> <span class="hljs-attr">name</span>",
             <span class="hljs-attr">minLength:</span> <span class="hljs-attr">3</span>,
             <span class="hljs-attr">maxLength:</span> <span class="hljs-attr">100</span>
           })}
         /&gt;</span></span>
         <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Input</span>
           <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span>
           <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password"</span>
           {<span class="hljs-attr">...register</span>("<span class="hljs-attr">password</span>", {
             <span class="hljs-attr">required:</span> "<span class="hljs-attr">Please</span> <span class="hljs-attr">enter</span> <span class="hljs-attr">Password</span>",
             <span class="hljs-attr">minLength:</span> { <span class="hljs-attr">value:</span> <span class="hljs-attr">8</span>, <span class="hljs-attr">message:</span> "<span class="hljs-attr">Too</span> <span class="hljs-attr">short</span>" }
           })}
         /&gt;</span></span>
         <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Button</span>
           <span class="hljs-attr">borderRadius</span>=<span class="hljs-string">"md"</span>
           <span class="hljs-attr">bg</span>=<span class="hljs-string">"cyan.600"</span>
           <span class="hljs-attr">_hover</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">bg:</span> "<span class="hljs-attr">cyan.200</span>" }}
           <span class="hljs-attr">variant</span>=<span class="hljs-string">"ghost"</span>
           <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>
         &gt;</span>
           Submit
         <span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span></span>
&lt;/VStack&gt;
</code></pre>
<p>The props you see for the <code>Button</code> component are similar to the CSS properties, so migrating to Chakra UI won’t be a problem.</p>
<p>Now let’s give prompt alerts to the user when they enter any invalid data.</p>
<p>Make a new component <code>AlertPop.js</code>.</p>
<p>Import the following code: </p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { Alert, AlertIcon, AlertTitle } <span class="hljs-keyword">from</span> <span class="hljs-string">"@chakra-ui/react"</span>;
</code></pre>
<p>Let's define a prop for displaying the error message.</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AlertPop</span> (<span class="hljs-params">props</span>) </span>{
 <span class="hljs-keyword">return</span> (
   <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Alert</span> <span class="hljs-attr">status</span>=<span class="hljs-string">"error"</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">AlertIcon</span> /&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">AlertTitle</span> <span class="hljs-attr">mr</span>=<span class="hljs-string">{2}</span>&gt;</span>{props.title}<span class="hljs-tag">&lt;/<span class="hljs-name">AlertTitle</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">Alert</span>&gt;</span></span>
 );
}
</code></pre>
<p>Now import this component into the root file, and under every input field type in the below logic:</p>
<pre><code class="lang-js">{errors.firstname &amp;&amp; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AlertPop</span> <span class="hljs-attr">title</span>=<span class="hljs-string">{errors.firstname.message}</span> /&gt;</span></span>}
{errors.lastname &amp;&amp; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AlertPop</span> <span class="hljs-attr">title</span>=<span class="hljs-string">{errors.lastname.message}</span> /&gt;</span></span>}
{errors.password &amp;&amp; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AlertPop</span> <span class="hljs-attr">title</span>=<span class="hljs-string">{errors.password.message}</span> /&gt;</span></span>}
</code></pre>
<p>Finally import <code>useToast</code> like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useToast } <span class="hljs-keyword">from</span> <span class="hljs-string">"@chakra-ui/react"</span>
</code></pre>
<p>Using this component, we’ll be able to to display a pop-up message when the user successfully submits the form.</p>
<p>Here’s how we will perform this:</p>
<pre><code class="lang-js">Import { useToast } <span class="hljs-keyword">from</span> “@chakra-ui/react”

<span class="hljs-keyword">const</span> toast = useToast( )
<span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
   <span class="hljs-comment">//console.log(data);</span>
   toast({
     <span class="hljs-attr">title</span>: <span class="hljs-string">"Submitted!"</span>,
     <span class="hljs-attr">status</span>: <span class="hljs-string">"success"</span>,
     <span class="hljs-attr">duration</span>: <span class="hljs-number">3000</span>,
     <span class="hljs-attr">isClosable</span>: <span class="hljs-literal">true</span>
   });

   setData(data);
 };
</code></pre>
<p>The end result should look something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/submit.png" alt="Toast component in action" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Web technology is advancing every day, at a very fast rate. It’s good to learn to use various libraries, but make sure you understand the basics first. </p>
<p>For example, you just can’t start learning ReactJS all of a sudden without understanding DOM manipulation. The basics are the foundation, else you won’t be able to understand the beauty of how the web works.</p>
<h2 id="heading-thanks-for-reading">Thanks for Reading!✨</h2>
<p>It’s good to see that you have read this far. If you did gain some insights from this article, feel free to share it with your community and co-workers. </p>
<p>I talk about web technologies and build projects, further documenting the development process for other developers to reference. If you need any guidance, make sure you hit me up on <a target="_blank" href="https://twitter.com/BrodasGeo">Twitter</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build React Forms the Easy Way with react-hook-form ]]>
                </title>
                <description>
                    <![CDATA[ Nobody enjoys creating and re-creating complex forms with validation, React developers included. When it comes to building forms in React, it's essential to use a form library that provides a lot of convenient tools and doesn’t require much code. Bas... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-react-forms/</link>
                <guid isPermaLink="false">66d03776dcd3a41034854bbc</guid>
                
                    <category>
                        <![CDATA[ Form validations ]]>
                    </category>
                
                    <category>
                        <![CDATA[ forms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reed ]]>
                </dc:creator>
                <pubDate>Fri, 12 Mar 2021 16:39:02 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/03/how-to-build-react-forms.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Nobody enjoys creating and re-creating complex forms with validation, React developers included.</p>
<p>When it comes to building forms in React, it's essential to use a form library that provides a lot of convenient tools and doesn’t require much code.</p>
<p>Based off of these two criteria, utility and simplicity, the ideal React form library to use for your applications is <code>react-hook-form</code>.</p>
<p>Let's see how to use react-hook-form in your own projects to build rich, featureful forms for your React apps.</p>
<h2 id="heading-how-to-install-react-hook-form">How to Install react-hook-form</h2>
<p>Let’s cover a typical use case: a user signing up to our application. </p>
<p>For our signup form, we will have three inputs for any new user's username, password, and email:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> styles = {
  <span class="hljs-attr">container</span>: {
    <span class="hljs-attr">width</span>: <span class="hljs-string">"80%"</span>,
    <span class="hljs-attr">margin</span>: <span class="hljs-string">"0 auto"</span>,
  },
  <span class="hljs-attr">input</span>: {
    <span class="hljs-attr">width</span>: <span class="hljs-string">"100%"</span>,
  },
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Signup</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.container}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h4</span>&gt;</span>Sign up<span class="hljs-tag">&lt;/<span class="hljs-name">h4</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Username"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.input}</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Email"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.input}</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.input}</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Once we have a React project up and running, we’ll start by installing the <code>react-hook-form</code> library.</p>
<pre><code class="lang-bash">npm i react-hook-form
</code></pre>
<h2 id="heading-how-to-use-the-useform-hook">How to use the useForm hook</h2>
<p>To start using <code>react-hook-form</code> we just need to call the <code>useForm</code> hook. </p>
<p>When we do, we’ll get back an object from which we will destructure the <code>register</code> property.</p>
<p><code>register</code> is a function, which we need to connect to each one of the inputs as a ref. </p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { register } = useForm();

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.container}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h4</span>&gt;</span>Signup<span class="hljs-tag">&lt;/<span class="hljs-name">h4</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{register}</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Username"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.input}</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{register}</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Email"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.input}</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{register}</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.input}</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>The register function will take the value our user has typed into each input to validate it. Register will also pass each value to a function which will be called when our form is submitted, which we'll cover next.</p>
<p>For register to work properly, for each input we need to provide an appropriate name attribute. For example, for the username input, it will have a name of "username".</p>
<p>The reason for this is that when our form is submitted, we will get all of the inputs' values on a single object. Each of the object's properties will be named according to the inputs' name attributes that we have specified.</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { register } = useForm();

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.container}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h4</span>&gt;</span>My Form<span class="hljs-tag">&lt;/<span class="hljs-name">h4</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span>
          <span class="hljs-attr">ref</span>=<span class="hljs-string">{register}</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Username"</span>
          <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.input}</span>
        /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span>
          <span class="hljs-attr">ref</span>=<span class="hljs-string">{register}</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Email"</span>
          <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.input}</span>
        /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span>
          <span class="hljs-attr">ref</span>=<span class="hljs-string">{register}</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password"</span>
          <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.input}</span>
        /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h2 id="heading-how-to-submit-our-form-with-handlesubmit">How to submit our form with handleSubmit</h2>
<p>To handle submitting our form and receiving the input data, we’ll add an <code>onSubmit</code> to our form element and connect it to a local function with the same name:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { register } = useForm();

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onSubmit</span>(<span class="hljs-params"></span>) </span>{}

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.container}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h4</span>&gt;</span>My Form<span class="hljs-tag">&lt;/<span class="hljs-name">h4</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{onSubmit}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span>
          <span class="hljs-attr">ref</span>=<span class="hljs-string">{register}</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Username"</span>
          <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.input}</span>
        /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span>
          <span class="hljs-attr">ref</span>=<span class="hljs-string">{register}</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Email"</span>
          <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.input}</span>
        /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span>
          <span class="hljs-attr">ref</span>=<span class="hljs-string">{register}</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password"</span>
          <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.input}</span>
        /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>From <code>useForm</code>, we’ll grab a function called <code>handleSubmit</code> and wrap it around onSubmit as a higher-order function. </p>
<p>The <code>handleSubmit</code> function will take care of collecting all of our data typed into each input which we’ll receive within <code>onSubmit</code> as an object called <code>data</code>.</p>
<p>Now if we <code>console.log(data)</code> we can see what we typed into each of our inputs on a property with the same name:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { register, handleSubmit } = useForm();

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onSubmit</span>(<span class="hljs-params">data</span>) </span>{
    <span class="hljs-built_in">console</span>.log(data); 
    <span class="hljs-comment">// { username: 'test', email: 'test', password: 'test' }</span>
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.container}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h4</span>&gt;</span>Signup<span class="hljs-tag">&lt;/<span class="hljs-name">h4</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit(onSubmit)}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span>
          <span class="hljs-attr">ref</span>=<span class="hljs-string">{register}</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Username"</span>
          <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.input}</span>
        /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span>
          <span class="hljs-attr">ref</span>=<span class="hljs-string">{register}</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Email"</span>
          <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.input}</span>
        /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span>
          <span class="hljs-attr">ref</span>=<span class="hljs-string">{register}</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password"</span>
          <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.input}</span>
        /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h2 id="heading-validation-options-with-the-register-function">Validation options with the register function</h2>
<p>To validate our form and add constraints for each input’s value is very simple—we just need to pass information to the <code>register</code> function.</p>
<p><code>register</code> accepts an object, which includes a number of properties that will tell register how to validate a given input. </p>
<p>The first property is <code>required</code>. By default, it is set to false but we can set that to true to make sure the form isn’t submitted if it’s not filled out.</p>
<p>We want the username value to be required and we want our users’ usernames to be more than six characters but less than 24.</p>
<p>To apply this validation, we can set the constraint of <code>minLength</code> to six, but the <code>maxLength</code> should be 20:</p>
<pre><code class="lang-jsx">&lt;input
  name=<span class="hljs-string">"username"</span>
  ref={register({
    <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">minLength</span>: <span class="hljs-number">6</span>,
    <span class="hljs-attr">maxLength</span>: <span class="hljs-number">20</span>,
  })}
  style={styles.input}
  placeholder=<span class="hljs-string">"Username"</span>
/&gt;
</code></pre>
<p>If we were using numbers for this input (say if this input was for the person’s age), we would use the properties <code>min</code> and <code>max</code> instead of <code>minLength</code> and <code>maxLength</code>.</p>
<p>Next, we can supply a regex pattern if we like. </p>
<p>If we want a username to only contain uppercase and lowercase characters, we can use the following regex which allows for custom validation:</p>
<pre><code class="lang-jsx">&lt;input
  name=<span class="hljs-string">"username"</span>
  ref={register({
    <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">minLength</span>: <span class="hljs-number">6</span>,
    <span class="hljs-attr">maxLength</span>: <span class="hljs-number">20</span>,
    <span class="hljs-attr">pattern</span>: <span class="hljs-regexp">/^[A-Za-z]+$/i</span>,
  })}
  style={styles.input}
  placeholder=<span class="hljs-string">"Username"</span>
/&gt;
</code></pre>
<p>And finally, there is <code>validate</code>, a custom function that gives us access to the value typed into the input. <code>validate</code> allows us to provide our own logic to determine whether it is valid or not (by returning the boolean true or false).</p>
<p>For the email here, we also want it to be required and for it to be a valid email. To check this, we can pass the input to a function from the library <code>validator</code> called <code>isEmail</code>.</p>
<p>If the input is an email, it returns true. Otherwise, false:</p>
<pre><code class="lang-jsx">&lt;input
  name=<span class="hljs-string">"email"</span>
  ref={register({
    <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">validate</span>: <span class="hljs-function">(<span class="hljs-params">input</span>) =&gt;</span> isEmail(input), <span class="hljs-comment">// returns true if valid</span>
  })}
  style={styles.input}
  placeholder=<span class="hljs-string">"Email"</span>
/&gt;
</code></pre>
<p>For password’s <code>register</code> function, we’ll set required to true, <code>minlength</code> to six, and we won’t set a <code>maxLength</code>:</p>
<pre><code class="lang-jsx">&lt;input
  name=<span class="hljs-string">"password"</span>
  ref={register({
    <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">minLength</span>: <span class="hljs-number">6</span>
  })}
  style={styles.input}
  placeholder=<span class="hljs-string">"Password"</span>
/&gt;
</code></pre>
<h2 id="heading-how-to-display-errors">How to display errors</h2>
<p>Right now, if an input within our form isn’t valid, we don't tell our user that anything is wrong. We need to give them feedback to fix the values they have supplied.</p>
<p>When one of the inputs is invalid, the form data is merely not submitted (<code>onSubmit</code> isn’t called). Additionally, the first input with an error is automatically focused, which doesn’t provide our user any detailed feedback about what’s happening.</p>
<p>Instead of just not submitting the form, we can grab an <code>errors</code> object from useForm.</p>
<p>And just like the data function we get in <code>onSubmit</code>, <code>errors</code> contains properties corresponding to each of the inputs' names if it has an error.</p>
<p>For our example, we can add a conditional to each of the inputs and say if there is an error, we’ll set the <code>borderColor</code> to red.</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { register, handleSubmit, errors } = useForm();

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onSubmit</span>(<span class="hljs-params">data</span>) </span>{
    <span class="hljs-built_in">console</span>.log(data);
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.container}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h4</span>&gt;</span>My Form<span class="hljs-tag">&lt;/<span class="hljs-name">h4</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit(onSubmit)}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span>
          <span class="hljs-attr">ref</span>=<span class="hljs-string">{register({</span>
            <span class="hljs-attr">required:</span> <span class="hljs-attr">true</span>,
            <span class="hljs-attr">minLength:</span> <span class="hljs-attr">6</span>,
            <span class="hljs-attr">maxLength:</span> <span class="hljs-attr">20</span>,
            <span class="hljs-attr">pattern:</span> /^[<span class="hljs-attr">A-Za-z</span>]+$/<span class="hljs-attr">i</span>,
          })}
          <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">...styles.input</span>, <span class="hljs-attr">borderColor:</span> <span class="hljs-attr">errors.username</span> &amp;&amp; "<span class="hljs-attr">red</span>" }}
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Username"</span>
        /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span>
          <span class="hljs-attr">ref</span>=<span class="hljs-string">{register({</span>
            <span class="hljs-attr">required:</span> <span class="hljs-attr">true</span>,
            <span class="hljs-attr">validate:</span> (<span class="hljs-attr">input</span>) =&gt;</span> isEmail(input),
          })}
          style={{ ...styles.input, borderColor: errors.email &amp;&amp; "red" }}
          placeholder="Email"
        /&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span>
          <span class="hljs-attr">ref</span>=<span class="hljs-string">{register({</span>
            <span class="hljs-attr">required:</span> <span class="hljs-attr">true</span>,
            <span class="hljs-attr">minLength:</span> <span class="hljs-attr">6</span>,
          })}
          <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">...styles.input</span>, <span class="hljs-attr">borderColor:</span> <span class="hljs-attr">errors.password</span> &amp;&amp; "<span class="hljs-attr">red</span>" }}
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password"</span>
        /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">disabled</span>=<span class="hljs-string">{formState.isSubmitting}</span>&gt;</span>
          Submit
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h2 id="heading-validation-mode">Validation mode</h2>
<p>You’ll notice, by default, that the errors object is updated only when we submit the form. The default validation is only performed upon submitting the form.</p>
<p>We can change this by passing the <code>useForm</code> an object, where we can set the mode to when we want validation to be performed: <code>onBlur</code>, <code>onChange</code>, or <code>onSubmit</code>. </p>
<p><code>onBlur</code> is going to make validation run whenever the user ‘blurs’ or clicks away from the input. <code>onChange</code> is whenever a user types in the input, and <code>onSubmit</code> is whenever the form submitted.</p>
<p>For our form, let's select <code>onBlur</code>.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> { register, handleSubmit, errors } = useForm({
  <span class="hljs-attr">mode</span>: <span class="hljs-string">"onBlur"</span>,
});
</code></pre>
<p>Note that there are other helpers to both set and clear the errors manually (<code>setError</code> and <code>clearError</code>). These would be used if, for example, you had certain cases where you want it to create a different error or clear an error yourself within <code>onSubmit</code>.</p>
<h2 id="heading-how-to-disable-our-form-with-formstate">How to disable our form with formState</h2>
<p>The last value which we can get the <code>useForm</code> hook is <code>formState</code>.</p>
<p>It gives us important information such as when certain inputs have been touched, as well as when the form has been submitted.</p>
<p>So if you want to disable your form’s button to make sure the form isn’t submitted more times than it needs to, we could set disabled to <code>formState.isSubmitting</code>.</p>
<p>Whenever we’re submitting our form, it’s going to be disabled until it’s done with validation and running our onSubmit function.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope that this article showed you how to more easily create functional forms within your React apps.</p>
<p>It's worth nothing that there are a ton more features that come with <code>react-hook-form</code> that I didn’t cover here.  The <a target="_blank" href="https://react-hook-form.com">documentation</a> should cover any use case you can think of.</p>
<p>If you are interested in seeing the final version of our code, click on the CodeSandbox link <a target="_blank" href="https://codesandbox.io/s/crazy-leavitt-nf74y">right here</a>.</p>
<h2 id="heading-become-a-professional-react-developer">Become a Professional React Developer</h2>
<p>React is hard. You shouldn't have to figure it out yourself.</p>
<p>I've put everything I know about React into a single course, to help you reach your goals in record time:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><strong>Introducing: The React Bootcamp</strong></a></p>
<p><strong>It’s the one course I wish I had when I started learning React.</strong></p>
<p>Click below to try the React Bootcamp for yourself:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><img src="https://reedbarger.nyc3.digitaloceanspaces.com/reactbootcamp/react-bootcamp-cta-alt.png" alt="Click to join the React Bootcamp" width="600" height="400" loading="lazy"></a>
<em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Data Validation – How to Check User Input on HTML Forms with Example JavaScript Code ]]>
                </title>
                <description>
                    <![CDATA[ Forms are ubiquitous in web applications. Some apps use forms to collect data to sign up users and provide an email address. Others use them to fulfill online transactions to facilitate a shopping experience.  You might use some web forms to apply fo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/form-validation-with-html5-and-javascript/</link>
                <guid isPermaLink="false">66b99cd23cd81de09c96b2cf</guid>
                
                    <category>
                        <![CDATA[ Form validations ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML5 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Shruti Kapoor ]]>
                </dc:creator>
                <pubDate>Mon, 18 Jan 2021 17:56:53 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/6003768298be260817e4aadc.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Forms are ubiquitous in web applications. Some apps use forms to collect data to sign up users and provide an email address. Others use them to fulfill online transactions to facilitate a shopping experience. </p>
<p>You might use some web forms to apply for a new car loan, whereas you'll use others to order pizza for dinner. So it's important that the data collected from those forms is cleaned, formatted correctly, and devoid of any malicious code. This process is called form validation.</p>
<p>We need form validation anytime we are accepting user input. We must ensure that the data entered is in the correct format, lies within a valid range of data (such as for date fields), and does not contain malicious code that could lead to SQL injections. Malformed or missing data can also cause the API to throw errors.</p>
<h2 id="heading-what-are-the-different-types-of-form-validations">What are the different types of form validations?</h2>
<p>Form validation can happen on the client side and the server side.</p>
<p>Client side validation occurs using HTML5 attributes and client side JavaScript. </p>
<p>You may have noticed that in some forms, as soon as you enter an invalid email address, the form gives an error "Please enter a valid email". This immediate type of validation is usually done via client side JavaScript.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/form-validation-cc.gif" alt="Validation error for incorrect credit card number" width="600" height="400" loading="lazy"></p>
<p>In other cases, you may have noticed that when you fill out a form and enter details such as a credit card, it may show a loading screen and then show an error "This credit card is invalid". </p>
<p>Here, the form made a call to its server side code, and returned a validation error after performing additional credit card checks. This validation case where a server-side call is made is called server side validation.</p>
<h2 id="heading-what-data-should-be-validated">What data should be validated?</h2>
<p>Form validation is needed anytime you accept data from a user. This may include:</p>
<ol>
<li>Validating the format of fields such as email address, phone number, zip code, name, password.</li>
<li>Validating mandatory fields</li>
<li>Checking the type of data such as string vs number for fields such as social security number.</li>
<li>Ensuring that the value entered is a valid value such as country, date, and so on.</li>
</ol>
<h2 id="heading-how-to-set-up-client-side-validation">How to set up client side validation</h2>
<p>On the client side, validation can be done in two ways:</p>
<ol>
<li>Using HTML5 functionality</li>
<li>Using JavaScript</li>
</ol>
<h3 id="heading-how-to-set-up-validation-with-html5-functionality">How to set up validation with HTML5 functionality</h3>
<p>HTML5 provides a bunch of attributes to help validate data. Here are some common validation cases:</p>
<ul>
<li>Making fields required using <code>required</code></li>
<li>Constraining the length of data:<ul>
<li><code>minlength</code>, <code>maxlength</code>: for text data</li>
<li><code>min</code> and <code>max</code> for max value of num type</li>
</ul>
</li>
<li>Restricting the type of data using <code>type</code>:<ul>
<li><code>&lt;input type="email" name="multiple&gt;</code></li>
</ul>
</li>
<li>Specifying data patterns using <code>pattern</code>:<ul>
<li>specifies a regex pattern that the entered form data needs to match</li>
</ul>
</li>
</ul>
<p>When the input value matches the above HTML5 validation, it gets assigned a psuedo-class <code>:valid</code>, and <code>:invalid</code> if it doesn't.</p>
<p>Let's try an example:</p>
<pre><code class="lang-HTML"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"firstname"</span>&gt;</span> First Name: <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"firstname"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"firstname"</span> <span class="hljs-attr">required</span> <span class="hljs-attr">maxlength</span>=<span class="hljs-string">"45"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"lastname"</span>&gt;</span> Last Name: <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"lastname"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"lastname"</span> <span class="hljs-attr">required</span> <span class="hljs-attr">maxlength</span>=<span class="hljs-string">"45"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/form-validation-required.png" alt="Client side form validation for required fields using HTML5 attributes" width="600" height="400" loading="lazy"></p>
<p><a target="_blank" href="https://jsfiddle.net/58xc2qyj/">Link to JSFiddle</a></p>
<p>Here we have two required fields - First Name and Last Name. Try this example in JSFidle. If you skip either of these fields and press submit, you'll get a message, "Please fill out this field". This is validation using in-built HTML5.</p>
<h3 id="heading-how-to-set-up-validation-using-javascript">How to set up validation using JavaScript</h3>
<p>When implementing form validation, there are a few things to consider:</p>
<ol>
<li>What is defined as "valid" data? This helps you answer questions about the format, length, required fields, and type of data.</li>
<li>What happens when invalid data is entered? This will help you define the user experience of the validation - whether to show an error message inline or at the top of the form, how detailed should the error message be, should the form be sumitted anyways, should there be analytics to track invalid format of data? And so on.</li>
</ol>
<p>You can perform JavaScript validation in two ways:</p>
<ol>
<li>Inline validation using JavaScript</li>
<li>HTML5 Constraint validation API</li>
</ol>
<h4 id="heading-inline-validation-using-javascript">Inline validation using JavaScript</h4>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"form"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"firstname"</span>&gt;</span> First Name* <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"firstname"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"firstname"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">role</span>=<span class="hljs-string">"alert"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"nameError"</span> <span class="hljs-attr">aria-hidden</span>=<span class="hljs-string">"true"</span>&gt;</span>
    Please enter First Name
  <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> submit = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"submit"</span>);

submit.addEventListener(<span class="hljs-string">"click"</span>, validate);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">validate</span>(<span class="hljs-params">e</span>) </span>{
  e.preventDefault();

  <span class="hljs-keyword">const</span> firstNameField = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"firstname"</span>);
  <span class="hljs-keyword">let</span> valid = <span class="hljs-literal">true</span>;

  <span class="hljs-keyword">if</span> (!firstNameField.value) {
    <span class="hljs-keyword">const</span> nameError = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"nameError"</span>);
    nameError.classList.add(<span class="hljs-string">"visible"</span>);
    firstNameField.classList.add(<span class="hljs-string">"invalid"</span>);
    nameError.setAttribute(<span class="hljs-string">"aria-hidden"</span>, <span class="hljs-literal">false</span>);
    nameError.setAttribute(<span class="hljs-string">"aria-invalid"</span>, <span class="hljs-literal">true</span>);
  }
  <span class="hljs-keyword">return</span> valid;
}
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-id">#nameError</span> {
  <span class="hljs-attribute">display</span>: none;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">0.8em</span>;
}

<span class="hljs-selector-id">#nameError</span><span class="hljs-selector-class">.visible</span> {
  <span class="hljs-attribute">display</span>: block;
}

<span class="hljs-selector-tag">input</span><span class="hljs-selector-class">.invalid</span> {
  <span class="hljs-attribute">border-color</span>: red;
}
</code></pre>
<p><a target="_blank" href="https://jsfiddle.net/0tq3e49w/4/">Link to JSFiddle</a></p>
<p>In this example, we check for required fields using JavaScript. If a required field is not present, we use CSS to show the error message. </p>
<p>Aria labels are modified accordingly to signal an error. By using CSS to show / hide an error, we are reducing the number of DOM manipulations we need to make. The error message is provided in-context thereby making the user experience intuitive.</p>
<h4 id="heading-html5-constraint-validation-api">HTML5 Constraint validation API</h4>
<p>The <code>required</code> and <code>pattern</code> HTML attributes can help perform basic validation. But if you want more complex validation or want to provide detailed error messaging, you can use the Constraint Validation API. </p>
<p>Some methods provided by this API are:</p>
<ol>
<li><code>checkValidity</code></li>
<li><code>setCustomValidity</code></li>
<li><code>reportValidity</code></li>
</ol>
<p>The following properties are useful:</p>
<ol>
<li><code>validity</code></li>
<li><code>validationMessage</code></li>
<li><code>willValidate</code></li>
</ol>
<p>In this example, we will validate using HTML5 inbuilt methods such as <code>required</code> and <code>length</code> in conjunction with the Constraint Validation API to provide detailed error messages.</p>
<pre><code class="lang-HTML"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"firstname"</span>&gt;</span> First Name: <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"firstname"</span> <span class="hljs-attr">required</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"firstname"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> nameField = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"input"</span>);

nameField.addEventListener(<span class="hljs-string">"input"</span>, <span class="hljs-function">() =&gt;</span> {
  nameField.setCustomValidity(<span class="hljs-string">""</span>);
  nameField.checkValidity();
  <span class="hljs-built_in">console</span>.log(nameField.checkValidity());
});

nameField.addEventListener(<span class="hljs-string">"invalid"</span>, <span class="hljs-function">() =&gt;</span> {
  nameField.setCustomValidity(<span class="hljs-string">"Please fill in your First Name."</span>);
});
</code></pre>
<p><a target="_blank" href="https://jsfiddle.net/xz2wjLck/1/">Link to JSFiddle</a></p>
<h2 id="heading-dont-forget-server-side-validation">Don't forget server side validation</h2>
<p>Client side validation is not the only validation check you should do. You must also validate the data received from your client on the server side code to ensure that the data matches what you expect it to be. </p>
<p>You can also use server-side validation to perform business logic verifications that should not live on the client side.</p>
<h2 id="heading-form-validation-best-practices">Form Validation best practices</h2>
<ol>
<li>Always have server side validation, since malicious actors can bypass client side validation.</li>
<li>Provide detailed error messages in-context with the field that produced the error.</li>
<li>Provide an example of what the data should look like in case of an error message, such as - "Email did not match format - test@example.com"</li>
<li>Avoid using single error pages that involve redirection. This is bad user experience and forces the user to go back to a previous page to fix the form and lose context.</li>
<li>Always mark required fields.</li>
</ol>
<h3 id="heading-interested-in-more-tutorials-and-articles-like-this-sign-up-for-my-newsletterhttpstinylettercomshrutikapoor-or-follow-me-on-twitterhttpstwittercomshrutikapoor08">Interested in more tutorials and articles like this? <a target="_blank" href="https://tinyletter.com/shrutikapoor">Sign up for my newsletter.</a> or <a target="_blank" href="https://twitter.com/shrutikapoor08">follow me on Twitter</a></h3>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Generic Form Validator in Angular ]]>
                </title>
                <description>
                    <![CDATA[ By Victor Onwuzor Building an Angular application that involves many forms can be stressful. Especially so when you have to handle the validation messages on each component.  One way to reduce your stress is to write a generic validation class that h... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/angular-generic-form-validator/</link>
                <guid isPermaLink="false">66d461713dce891ac3a96838</guid>
                
                    <category>
                        <![CDATA[ Angular ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Form validations ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 03 Nov 2020 17:22:23 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/10/461803-angular-JavaScript-HTML-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Victor Onwuzor</p>
<p>Building an Angular application that involves many forms can be stressful. Especially so when you have to handle the validation messages on each component. </p>
<p>One way to reduce your stress is to write a generic validation class that handles all your validation messages.</p>
<p>On the one hand, this will significantly reduce the code on your HTML template. It will also give you one source of error messages with the flexibility to override the error message on each component</p>
<p>On the other, it involves writing a little more code on the component and extra files</p>
<p>But I think the pros outweigh the cons when dealing with multiple forms in different components.</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<ul>
<li>Basic knowledge of Angular</li>
<li>Basic knowledge of reactive forms</li>
</ul>
<h2 id="heading-what-we-are-building">What we are building</h2>
<p>Angular has two types of forms: template driven forms and reactive forms. In this post, we will focus on reactive forms.</p>
<p>We will learn how to validate a simple Login and Sign up form with generic validation using a reactive form. I used the Bulma CSS framework for the design. </p>
<p>The form input values are just console log when you click on submit. I did this so that we can focus mainly on form validation, but you can do whatever you want with the form input values. </p>
<p>Here is the demo link on <a target="_blank" href="https://stackblitz.com/github/onwuvic/generic-reactive-form-validation">Stackblitz</a>.</p>
<h2 id="heading-step-1-setup">Step 1: Setup</h2>
<p>I have created a starter file for this project with all the HTML, CSS, and Bulma done. This allows us to focus more on the generic form validation. Clone this repo on <a target="_blank" href="https://github.com/onwuvic/generic-reactive-form-validation">GitHub here</a>.</p>
<p>Then, in your terminal run this command:</p>
<pre><code>git clone git@github.com:onwuvic/generic-reactive-form-validation.git
</code></pre><p>Or you can do this:</p>
<pre><code>git clone https:<span class="hljs-comment">//github.com/onwuvic/generic-reactive-form-validation.git</span>
</code></pre><pre><code>cd generic-reactive-form-validation
</code></pre><pre><code>git checkout starter
</code></pre><pre><code class="lang-cmd">npm install
</code></pre>
<pre><code>ng serve
</code></pre><p>Next, visit <a target="_blank" href="http://localhost:4200/">http://localhost:4200/</a> on your browser.</p>
<p>Open the generic-reactive-form-validation folder in any of your editors. The file structure should look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/Screenshot-2020-11-02-at-09.22.45.png" alt="Image" width="600" height="400" loading="lazy">
<em>file structure</em></p>
<h2 id="heading-step-2-import-reactiveformsmodule">Step 2: Import ReactiveFormsModule</h2>
<p>Now, let's import <code>ReactiveFormsModule</code> into our app module and add it to the <code>imports</code> array.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { BrowserModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/platform-browser'</span>;
<span class="hljs-keyword">import</span> { NgModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { ReactiveFormsModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;

<span class="hljs-keyword">import</span> { AppRoutingModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app-routing.module'</span>;
<span class="hljs-keyword">import</span> { AppComponent } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.component'</span>;
<span class="hljs-keyword">import</span> { LoginComponent } <span class="hljs-keyword">from</span> <span class="hljs-string">'./modules/login/login.component'</span>;
<span class="hljs-keyword">import</span> { SignUpComponent } <span class="hljs-keyword">from</span> <span class="hljs-string">'./modules/sign-up/sign-up.component'</span>;

<span class="hljs-meta">@NgModule</span>({
  declarations: [
    AppComponent,
    LoginComponent,
    SignUpComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule { }
</code></pre>
<h2 id="heading-step-3-create-a-generic-validation-class-and-password-confirmation-validator">Step 3: Create a generic validation class and password confirmation validator</h2>
<h3 id="heading-generic-validation-class">Generic validation class</h3>
<p>Let's create a shared folder inside the root app folder. Then inside the shared folder, create a generic-validator.ts file. Write the following code:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { FormGroup } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;

<span class="hljs-comment">// Provide all set of validation messages here</span>
<span class="hljs-keyword">const</span> VALIDATION_MESSAGES = {
  email: {
    required: <span class="hljs-string">'Required'</span>,
    email: <span class="hljs-string">'This email is invalid'</span>
  },
  password: {
    required: <span class="hljs-string">'Required'</span>,
    minlength: <span class="hljs-string">'The password length must be greater than or equal to 8'</span>
  },
  confirmPassword: {
    required: <span class="hljs-string">'Required'</span>,
    match: <span class="hljs-string">'Password does not match'</span>
  },
  firstName: {
    required: <span class="hljs-string">'Required'</span>
  },
  lastName: {
    required: <span class="hljs-string">'Required'</span>
  }
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> GenericValidator {
  <span class="hljs-comment">// By default the defined set of validation messages is pass but a custom message when the class is called can also be passed</span>
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> validationMessages: { [key: <span class="hljs-built_in">string</span>]: { [key: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">string</span> } } = VALIDATION_MESSAGES</span>) {}

  <span class="hljs-comment">// this will process each formcontrol in the form group</span>
  <span class="hljs-comment">// and then return the error message to display</span>
  <span class="hljs-comment">// the return value will be in this format `formControlName: 'error message'`;</span>
  processMessages(container: FormGroup): { [key: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">string</span> } {
    <span class="hljs-keyword">const</span> messages = {};
    <span class="hljs-comment">// loop through all the formControls</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> controlKey <span class="hljs-keyword">in</span> container.controls) {
      <span class="hljs-keyword">if</span> (container.controls.hasOwnProperty(controlKey)) {
        <span class="hljs-comment">// get the properties of each formControl</span>
        <span class="hljs-keyword">const</span> controlProperty = container.controls[controlKey];
        <span class="hljs-comment">// If it is a FormGroup, process its child controls.</span>
        <span class="hljs-keyword">if</span> (controlProperty <span class="hljs-keyword">instanceof</span> FormGroup) {
          <span class="hljs-keyword">const</span> childMessages = <span class="hljs-built_in">this</span>.processMessages(controlProperty);
          <span class="hljs-built_in">Object</span>.assign(messages, childMessages);
        } <span class="hljs-keyword">else</span> {
          <span class="hljs-comment">// Only validate if there are validation messages for the control</span>
          <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.validationMessages[controlKey]) {
            messages[controlKey] = <span class="hljs-string">''</span>;
            <span class="hljs-keyword">if</span> ((controlProperty.dirty || controlProperty.touched) &amp;&amp; controlProperty.errors) {
              <span class="hljs-comment">// loop through the object of errors</span>
              <span class="hljs-built_in">Object</span>.keys(controlProperty.errors).map(<span class="hljs-function"><span class="hljs-params">messageKey</span> =&gt;</span> {
                <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.validationMessages[controlKey][messageKey]) {
                  messages[controlKey] += <span class="hljs-built_in">this</span>.validationMessages[controlKey][messageKey] + <span class="hljs-string">' '</span>;
                }
              });
            }
          }
        }
      }
    }
    <span class="hljs-keyword">return</span> messages;
  }
}
</code></pre>
<p>First, we import the <code>FormGroup</code>. We can write all our validation messages in this file or pass each form validation message from their component. </p>
<p>Each property on the <code>VALIDATION_MESSAGES</code> object corresponds to each input field name or <code>formControlName</code>. Also, each property of the input field corresponds to the validation name on it. Its value is what you want to show as the error message. </p>
<p>For instance, the input field name <code>formControlName</code> "email" has validations of “required” and “email” on it.</p>
<p>In constructor method, we can override the default error messages from the component where our generic validation is being used by passing the validation message when we instantiate our generic validation class.</p>
<p>The processMessages method processes each form input field and returns the error message to display.</p>
<h3 id="heading-password-confirmation-validation">Password confirmation validation</h3>
<p>Now, let’s create a password confirmation validator to check if our password and confirm password match.</p>
<p>Inside the shared folder, create a <code>password-matcher.ts</code> file. Write the following code:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { AbstractControl } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> PasswordMatcher {
  <span class="hljs-keyword">static</span> match(control: AbstractControl): <span class="hljs-built_in">void</span> | <span class="hljs-literal">null</span> {
    <span class="hljs-keyword">const</span> passwordControl = control.get(<span class="hljs-string">'password'</span>);
    <span class="hljs-keyword">const</span> confirmPasswordControl = control.get(<span class="hljs-string">'confirmPassword'</span>);

    <span class="hljs-keyword">if</span> (passwordControl.pristine || confirmPasswordControl.pristine) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
    }

    <span class="hljs-keyword">if</span> (passwordControl.value === confirmPasswordControl.value) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
    }

    confirmPasswordControl.setErrors({ match: <span class="hljs-literal">true</span> });
  }
}
</code></pre>
<h2 id="heading-step-4-add-formgroup-and-formbuilder-to-each-components-and-templates">Step 4: Add FormGroup and FormBuilder to each components and templates</h2>
<h3 id="heading-sign-up-form-component">Sign up form component</h3>
<p>Inside the app/modules/sign-up, add the below code to the sign-up component:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { Component, OnInit } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { FormGroup, FormBuilder, Validators } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;

<span class="hljs-keyword">import</span> { PasswordMatcher } <span class="hljs-keyword">from</span> <span class="hljs-string">'../../shared/password-matcher'</span>;

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'app-sign-up'</span>,
  templateUrl: <span class="hljs-string">'./sign-up.component.html'</span>,
  styleUrls: [<span class="hljs-string">'./sign-up.component.scss'</span>]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> SignUpComponent <span class="hljs-keyword">implements</span> OnInit {
  signupForm: FormGroup;

  <span class="hljs-comment">// Use with the generic validation message class</span>
  displayMessage: { [key: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">string</span> } = {};

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> fb: FormBuilder</span>) {}

  ngOnInit() {
    <span class="hljs-built_in">this</span>.signupForm = <span class="hljs-built_in">this</span>.fb.group({
      firstName: [<span class="hljs-string">''</span>, [Validators.required]],
      lastName: [<span class="hljs-string">''</span>, [Validators.required]],
      email: [<span class="hljs-string">''</span>, [Validators.required, Validators.email]],
      password: [<span class="hljs-string">''</span>, [Validators.required, Validators.minLength(<span class="hljs-number">8</span>)]],
      confirmPassword: [<span class="hljs-string">''</span>, Validators.required]
    }, { validator: PasswordMatcher.match });
  }

  signup() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'---form'</span>, <span class="hljs-built_in">this</span>.signupForm.value);
  }

}
</code></pre>
<p>We have Angular in-built validations for each input field along with our custom <code>PasswordMatcher</code> validation to ensure that the password and confirmed password match.</p>
<h3 id="heading-sign-up-form-template">Sign up form template</h3>
<p>Now let's have a look at the sign up form template:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"title is-4"</span>&gt;</span>Sign Up<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"description"</span>&gt;</span>Let's get started!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">form</span> (<span class="hljs-attr">ngSubmit</span>)=<span class="hljs-string">"signup()"</span> [<span class="hljs-attr">formGroup</span>]=<span class="hljs-string">"signupForm"</span> <span class="hljs-attr">novalidate</span> <span class="hljs-attr">autocomplete</span>=<span class="hljs-string">"false"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"field"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"control"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> [<span class="hljs-attr">ngClass</span>]=<span class="hljs-string">"{'is-danger': displayMessage.firstName}"</span> <span class="hljs-attr">formControlName</span>=<span class="hljs-string">"firstName"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input is-medium"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"First Name"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"displayMessage.firstName"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"help is-danger"</span>&gt;</span>
        {{ displayMessage.firstName }}
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"field"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"control"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> [<span class="hljs-attr">ngClass</span>]=<span class="hljs-string">"{'is-danger': displayMessage.lastName}"</span> <span class="hljs-attr">formControlName</span>=<span class="hljs-string">"lastName"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input is-medium"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Last Name"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"displayMessage.lastName"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"help is-danger"</span>&gt;</span>
        {{ displayMessage.lastName }}
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"field"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"control"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> [<span class="hljs-attr">ngClass</span>]=<span class="hljs-string">"{'is-danger': displayMessage.email}"</span> <span class="hljs-attr">formControlName</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input is-medium"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Email"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"displayMessage.email"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"help is-danger"</span>&gt;</span>
        {{ displayMessage.email }}
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"field"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"control"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> [<span class="hljs-attr">ngClass</span>]=<span class="hljs-string">"{'is-danger': displayMessage.password || displayMessage.confirmPassword }"</span> <span class="hljs-attr">formControlName</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input is-medium"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"displayMessage.password"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"help is-danger"</span>&gt;</span>
        {{ displayMessage.password }}
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"field"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"control"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> [<span class="hljs-attr">ngClass</span>]=<span class="hljs-string">"{'is-danger': displayMessage.confirmPassword}"</span> <span class="hljs-attr">formControlName</span>=<span class="hljs-string">"confirmPassword"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input is-medium"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Confirm Password"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"displayMessage.confirmPassword"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"help is-danger"</span>&gt;</span>
        {{ displayMessage.confirmPassword }}
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"button is-block is-primary is-fullwidth is-medium"</span> [<span class="hljs-attr">disabled</span>]=<span class="hljs-string">"signupForm.invalid"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">small</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"has-text-centered"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">em</span>&gt;</span>
      Already have an account
      <span class="hljs-tag">&lt;<span class="hljs-name">a</span> [<span class="hljs-attr">routerLink</span>]=<span class="hljs-string">"['']"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"primary-color"</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">em</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">small</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> (<span class="hljs-attr">ngSubmit</span>)=<span class="hljs-string">"signup()"</span> [<span class="hljs-attr">formGroup</span>]=<span class="hljs-string">"signupForm"</span> <span class="hljs-attr">novalidate</span> <span class="hljs-attr">autocomplete</span>=<span class="hljs-string">"false"</span>&gt;</span>
</code></pre>
<p>We added our <code>ngSubmit</code> and <code>formGroup</code> to the form tag.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> [<span class="hljs-attr">ngClass</span>]=<span class="hljs-string">"{'is-danger': displayMessage.firstName}"</span> <span class="hljs-attr">formControlName</span>=<span class="hljs-string">"firstName"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input is-medium"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"First Name"</span>&gt;</span>
</code></pre>
<p>We also added <code>formControlName</code> to each input field. If the display message has a firstName error message it will apply the ngClass is-danger to the input field.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"displayMessage.firstName"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"help is-danger"</span>&gt;</span>
  {{ displayMessage.firstName }}
<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>This displays our error message.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"button is-block is-primary is-fullwidth is-medium"</span> [<span class="hljs-attr">disabled</span>]=<span class="hljs-string">"signupForm.invalid"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>We disable the submit button if the form is not valid.</p>
<h3 id="heading-login-form-component">Login form component</h3>
<p>Inside the app/modules/login, add the below code to the login component:</p>
<pre><code class="lang-typescript">
<span class="hljs-keyword">import</span> { Component, OnInit } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { FormGroup, FormBuilder, Validators } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'app-login'</span>,
  templateUrl: <span class="hljs-string">'./login.component.html'</span>,
  styleUrls: [<span class="hljs-string">'./login.component.scss'</span>]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> LoginComponent <span class="hljs-keyword">implements</span> OnInit, AfterViewInit {
  loginForm: FormGroup;

  <span class="hljs-comment">// Use with the generic validation message class</span>
  displayMessage: { [key: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">string</span> } = {};
  <span class="hljs-keyword">private</span> validationMessages: { [key: <span class="hljs-built_in">string</span>]: { [key: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">string</span> } };

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> fb: FormBuilder</span>) {
    <span class="hljs-comment">// Defines all of the validation messages for the form.</span>
    <span class="hljs-built_in">this</span>.validationMessages = {
      email: {
        required: <span class="hljs-string">'Required'</span>,
        email: <span class="hljs-string">'This email is invalid'</span>
      },
      password: {
        required: <span class="hljs-string">'Required'</span>,
        minlength: <span class="hljs-string">'The password length must be greater than or equal to 8'</span>
      }
    };
  }

  ngOnInit() {
    <span class="hljs-built_in">this</span>.loginForm = <span class="hljs-built_in">this</span>.fb.group({
      email: [<span class="hljs-string">''</span>, [Validators.required, Validators.email]],
      password: [<span class="hljs-string">''</span>, [Validators.required, Validators.minLength(<span class="hljs-number">8</span>)]],
    });
  }

  login() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'---form'</span>, <span class="hljs-built_in">this</span>.loginForm.value);
  }

}
</code></pre>
<p>The only difference here with the sign up component is that we will be overriding the default error message in our generic validation class with the validation message.</p>
<h3 id="heading-login-form-template">Login form template</h3>
<p>Write the following code in the login template:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"title is-4"</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"description"</span>&gt;</span>Welcome back!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">form</span> (<span class="hljs-attr">ngSubmit</span>)=<span class="hljs-string">"login()"</span> [<span class="hljs-attr">formGroup</span>]=<span class="hljs-string">"loginForm"</span> <span class="hljs-attr">novalidate</span> <span class="hljs-attr">autocomplete</span>=<span class="hljs-string">"false"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"field"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"control"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> [<span class="hljs-attr">ngClass</span>]=<span class="hljs-string">"{'is-danger': displayMessage.email}"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input is-medium"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Email"</span> <span class="hljs-attr">formControlName</span>=<span class="hljs-string">"email"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"displayMessage.email"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"help is-danger"</span>&gt;</span>
        {{ displayMessage.email }}
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"field"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"control"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> [<span class="hljs-attr">ngClass</span>]=<span class="hljs-string">"{'is-danger': displayMessage.password}"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input is-medium"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password"</span> <span class="hljs-attr">formControlName</span>=<span class="hljs-string">"password"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"displayMessage.password"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"help is-danger"</span>&gt;</span>
        {{ displayMessage.password }}
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"button is-block is-primary is-fullwidth is-medium"</span> [<span class="hljs-attr">disabled</span>]=<span class="hljs-string">"loginForm.invalid"</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">small</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"has-text-centered"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">em</span>&gt;</span>
      Don't have an account
      <span class="hljs-tag">&lt;<span class="hljs-name">a</span> [<span class="hljs-attr">routerLink</span>]=<span class="hljs-string">"['signup']"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"primary-color"</span>&gt;</span>Sign Up<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">em</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">small</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<h2 id="heading-step-5-use-generic-validation-in-each-component">Step 5: Use Generic Validation in each component</h2>
<h3 id="heading-generic-validation-on-sign-up">Generic validation on Sign up</h3>
<p>Add the following code to the <code>sign-up.component.ts</code> file:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { Component, OnInit, ViewChildren, ElementRef, AfterViewInit } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { FormGroup, FormBuilder, Validators, FormControlName, AbstractControl } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;
<span class="hljs-keyword">import</span> { Observable, fromEvent, merge } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs'</span>;
<span class="hljs-keyword">import</span> { debounceTime } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs/operators'</span>;
<span class="hljs-keyword">import</span> { GenericValidator } <span class="hljs-keyword">from</span> <span class="hljs-string">'../../shared/generic-validator'</span>;
<span class="hljs-keyword">import</span> { PasswordMatcher } <span class="hljs-keyword">from</span> <span class="hljs-string">'../../shared/password-matcher'</span>;

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'app-sign-up'</span>,
  templateUrl: <span class="hljs-string">'./sign-up.component.html'</span>,
  styleUrls: [<span class="hljs-string">'./sign-up.component.scss'</span>]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> SignUpComponent <span class="hljs-keyword">implements</span> OnInit, AfterViewInit {
  <span class="hljs-comment">// Access every form input fields in our signup html file</span>
  <span class="hljs-meta">@ViewChildren</span>(FormControlName, { read: ElementRef }) formInputElements: ElementRef[];
  signupForm: FormGroup;

  <span class="hljs-comment">// Use with the generic validation message class</span>
  displayMessage: { [key: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">string</span> } = {};
  <span class="hljs-keyword">private</span> genericValidator: GenericValidator;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> fb: FormBuilder</span>) {
    <span class="hljs-comment">// Define an instance of the validator for use with this form,</span>
    <span class="hljs-built_in">this</span>.genericValidator = <span class="hljs-keyword">new</span> GenericValidator();
  }

  ngOnInit() {
    <span class="hljs-built_in">this</span>.signupForm = <span class="hljs-built_in">this</span>.fb.group({
      firstName: [<span class="hljs-string">''</span>, [Validators.required]],
      lastName: [<span class="hljs-string">''</span>, [Validators.required]],
      email: [<span class="hljs-string">''</span>, [Validators.required, Validators.email]],
      password: [<span class="hljs-string">''</span>, [Validators.required, Validators.minLength(<span class="hljs-number">8</span>)]],
      confirmPassword: [<span class="hljs-string">''</span>, Validators.required]
    }, { validator: PasswordMatcher.match });
  }

  ngAfterViewInit(): <span class="hljs-built_in">void</span> {
    <span class="hljs-comment">// Watch for the blur event from any input element on the form.</span>
    <span class="hljs-keyword">const</span> controlBlurs: Observable&lt;<span class="hljs-built_in">any</span>&gt;[] = <span class="hljs-built_in">this</span>.formInputElements
      .map(<span class="hljs-function">(<span class="hljs-params">formControl: ElementRef</span>) =&gt;</span> fromEvent(formControl.nativeElement, <span class="hljs-string">'blur'</span>));

    <span class="hljs-comment">// Merge the blur event observable with the valueChanges observable</span>
    merge(<span class="hljs-built_in">this</span>.signupForm.valueChanges, ...controlBlurs).pipe(
      debounceTime(<span class="hljs-number">800</span>)
    ).subscribe(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> {
      <span class="hljs-built_in">this</span>.displayMessage = <span class="hljs-built_in">this</span>.genericValidator.processMessages(<span class="hljs-built_in">this</span>.signupForm);
    });
  }

  signup() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'---form'</span>, <span class="hljs-built_in">this</span>.signupForm.value);
  }

}
</code></pre>
<p>Here we have imported the generic validation class.</p>
<pre><code>@ViewChildren(FormControlName, { <span class="hljs-attr">read</span>: ElementRef }) formInputElements: ElementRef[];
</code></pre><p>We added the <code>@ViewChildren</code> to access every form input field in our signup HTML file. This helps us listen for an event on them.</p>
<pre><code>private genericValidator: GenericValidator;

<span class="hljs-keyword">constructor</span>(private fb: FormBuilder) {
   <span class="hljs-comment">// Define an instance of the validator for use with this form</span>
   <span class="hljs-built_in">this</span>.genericValidator = <span class="hljs-keyword">new</span> GenericValidator();
}
</code></pre><p>We instantiate the Generic validation inside the constructor.</p>
<p>Then, we implement the ngAfterViewInit interface.</p>
<pre><code>ngAfterViewInit(): <span class="hljs-keyword">void</span> {
   <span class="hljs-comment">// Watch for the blur event from any </span>
   <span class="hljs-comment">// input element on the form.</span>
   <span class="hljs-keyword">const</span> controlBlurs: Observable&lt;any&gt;[] = <span class="hljs-built_in">this</span>.formInputElements
      .map(<span class="hljs-function">(<span class="hljs-params">formControl: ElementRef</span>) =&gt;</span>
         fromEvent(formControl.nativeElement, <span class="hljs-string">'blur'</span>)
      );
   <span class="hljs-comment">// Merge the blur event observable </span>
   <span class="hljs-comment">// with the valueChanges observable</span>
   merge(<span class="hljs-built_in">this</span>.signupForm.valueChanges, ...controlBlurs)
    .pipe(debounceTime(<span class="hljs-number">800</span>))
    .subscribe(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> {
      <span class="hljs-built_in">this</span>.displayMessage = <span class="hljs-built_in">this</span>.genericValidator
        .processMessages(<span class="hljs-built_in">this</span>.signupForm);
   });
}
</code></pre><p>Here we watch for the blur event from any input element on the form. </p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> controlBlurs: Observable&lt;<span class="hljs-built_in">any</span>&gt;[] = <span class="hljs-built_in">this</span>.formInputElements
      .map(<span class="hljs-function">(<span class="hljs-params">formControl: ElementRef</span>) =&gt;</span>
         fromEvent(formControl.nativeElement, <span class="hljs-string">'blur'</span>)
      );
</code></pre>
<pre><code class="lang-typescript">merge(<span class="hljs-built_in">this</span>.signupForm.valueChanges, ...controlBlurs)
    .pipe(debounceTime(<span class="hljs-number">800</span>))
    .subscribe(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> {
      <span class="hljs-built_in">this</span>.displayMessage = <span class="hljs-built_in">this</span>.genericValidator
        .processMessages(<span class="hljs-built_in">this</span>.signupForm);
   });
</code></pre>
<p>Now we have combined the form value changes observable (which gets triggered when any of the input values change) and the blur events of any input field into one observable. </p>
<p>So, when a user changes an input value or taps into any input field, this merge method gets triggered. </p>
<p>Then we add a delay of 800 milliseconds with <code>debounceTime(800)</code>. This gives the user time to make changes before trigging the validation. </p>
<p>Finally, we get the error messages to display by calling the generic validator method.</p>
<h3 id="heading-generic-validation-on-login">Generic validation on Login</h3>
<p>Write the following code to the <code>login.component.ts</code> file:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { Component, OnInit, ViewChildren, ElementRef, AfterViewInit } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { FormGroup, FormBuilder, Validators, FormControlName } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;
<span class="hljs-keyword">import</span> { Observable, fromEvent, merge } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs'</span>;
<span class="hljs-keyword">import</span> { debounceTime } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs/operators'</span>;
<span class="hljs-keyword">import</span> { GenericValidator } <span class="hljs-keyword">from</span> <span class="hljs-string">'../../shared/generic-validator'</span>;

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'app-login'</span>,
  templateUrl: <span class="hljs-string">'./login.component.html'</span>,
  styleUrls: [<span class="hljs-string">'./login.component.scss'</span>]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> LoginComponent <span class="hljs-keyword">implements</span> OnInit, AfterViewInit {
  <span class="hljs-comment">// Access every form input fields in our login html file</span>
  <span class="hljs-meta">@ViewChildren</span>(FormControlName, { read: ElementRef }) formInputElements: ElementRef[];
  loginForm: FormGroup;

  <span class="hljs-comment">// Use with the generic validation message class</span>
  displayMessage: { [key: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">string</span> } = {};
  <span class="hljs-keyword">private</span> validationMessages: { [key: <span class="hljs-built_in">string</span>]: { [key: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">string</span> } };
  <span class="hljs-keyword">private</span> genericValidator: GenericValidator;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> fb: FormBuilder</span>) {
    <span class="hljs-comment">// Defines all of the validation messages for the form.</span>
    <span class="hljs-built_in">this</span>.validationMessages = {
      email: {
        required: <span class="hljs-string">'Required'</span>,
        email: <span class="hljs-string">'This email is invalid'</span>
      },
      password: {
        required: <span class="hljs-string">'Required'</span>,
        minlength: <span class="hljs-string">'The password length must be greater than or equal to 8'</span>
      }
    };
    <span class="hljs-comment">// Define an instance of the validator for use with this form,</span>
    <span class="hljs-comment">// passing in this form's set of validation messages.</span>
    <span class="hljs-built_in">this</span>.genericValidator = <span class="hljs-keyword">new</span> GenericValidator(<span class="hljs-built_in">this</span>.validationMessages);
  }

  ngOnInit() {
    <span class="hljs-built_in">this</span>.loginForm = <span class="hljs-built_in">this</span>.fb.group({
      email: [<span class="hljs-string">''</span>, [Validators.required, Validators.email]],
      password: [<span class="hljs-string">''</span>, [Validators.required, Validators.minLength(<span class="hljs-number">8</span>)]],
    });
  }

  ngAfterViewInit(): <span class="hljs-built_in">void</span> {
    <span class="hljs-comment">// Watch for the blur event from any input element on the form.</span>
    <span class="hljs-keyword">const</span> controlBlurs: Observable&lt;<span class="hljs-built_in">any</span>&gt;[] = <span class="hljs-built_in">this</span>.formInputElements
      .map(<span class="hljs-function">(<span class="hljs-params">formControl: ElementRef</span>) =&gt;</span> fromEvent(formControl.nativeElement, <span class="hljs-string">'blur'</span>));

    <span class="hljs-comment">// Merge the blur event observable with the valueChanges observable</span>
    merge(<span class="hljs-built_in">this</span>.loginForm.valueChanges, ...controlBlurs).pipe(
      debounceTime(<span class="hljs-number">800</span>)
    ).subscribe(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> {
      <span class="hljs-built_in">this</span>.displayMessage = <span class="hljs-built_in">this</span>.genericValidator.processMessages(<span class="hljs-built_in">this</span>.loginForm);
    });
  }

  login() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'---form'</span>, <span class="hljs-built_in">this</span>.loginForm.value);
  }

}
</code></pre>
<p>The only difference here from the sign up code is that we are overriding our default validation messages with our new validation Messages specified in this component. Then we're passing it into the generic validation class when we instantiate it.</p>
<pre><code>  <span class="hljs-keyword">constructor</span>(private fb: FormBuilder) {
    <span class="hljs-comment">// Defines all of the validation messages for the form.</span>
    <span class="hljs-built_in">this</span>.validationMessages = {
      <span class="hljs-attr">email</span>: {
        <span class="hljs-attr">required</span>: <span class="hljs-string">'Required'</span>,
        <span class="hljs-attr">email</span>: <span class="hljs-string">'This email is invalid'</span>
      },
      <span class="hljs-attr">password</span>: {
        <span class="hljs-attr">required</span>: <span class="hljs-string">'Required'</span>,
        <span class="hljs-attr">minlength</span>: <span class="hljs-string">'The password length must be greater than or equal to 8'</span>
      }
    };
    <span class="hljs-comment">// Define an instance of the validator for use with this form,</span>
    <span class="hljs-comment">// passing in this form's set of validation messages.</span>
    <span class="hljs-built_in">this</span>.genericValidator = <span class="hljs-keyword">new</span> GenericValidator(<span class="hljs-built_in">this</span>.validationMessages);
  }
</code></pre><p>We can expected this to work the same way as the sign up generic validation.</p>
<p>And that's all you need to build a generic validator in Angular.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Creating a generic validator makes it easy to handle multiple form validations without using a ton of redundant code in your Angular application. </p>
<p>I hope this article was useful to you!</p>
<p>You can connect with me on <a target="_blank" href="https://www.linkedin.com/in/victoronwuzor/">LinkedIn</a> and <a target="_blank" href="https://twitter.com/victoronwuzor">Twitter</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Basic Form Validation in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ In the past, form validation would occur on the server, after a person had already entered in all of their information and pressed the submit button.  If the information was incorrect or missing, the server would have to send everything back with a m... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/basic-form-validation-in-javascript/</link>
                <guid isPermaLink="false">66c345500bafa8455505c681</guid>
                
                    <category>
                        <![CDATA[ Form validations ]]>
                    </category>
                
                    <category>
                        <![CDATA[ forms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 01 Feb 2020 00:00:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9d33740569d1a4ca3673.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In the past, form validation would occur on the server, after a person had already entered in all of their information and pressed the submit button. </p>
<p>If the information was incorrect or missing, the server would have to send everything back with a message telling the person to correct the form before submitting it again.</p>
<p>This was a lengthy process and would put a lot of the burden on the server.</p>
<p>These days, JavaScript provides a number of ways to validate a form's data right in the browser before sending it to the server.</p>
<p>Here's the HTML code we'll use in the following examples:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Form Validation<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span>&gt;</span><span class="javascript">
    <span class="hljs-comment">// Form validation will go here</span>
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"form"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">table</span> <span class="hljs-attr">cellspacing</span>=<span class="hljs-string">"2"</span> <span class="hljs-attr">cellpadding</span>=<span class="hljs-string">"2"</span> <span class="hljs-attr">border</span>=<span class="hljs-string">"1"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">td</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"right"</span>&gt;</span>Username<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"username"</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">td</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"right"</span>&gt;</span>Email Address<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"email-address"</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Submit"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"submit-btn"</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h2 id="heading-basic-validation">Basic Validation</h2>
<p>This type of validation involves checking all the mandatory fields and making sure they're properly filled in.</p>
<p>Here's a basic example of a function <code>validate</code> that shows an alert if the username and email address inputs are blank, otherwise it returns true:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> submitBtn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'submit-btn'</span>);

<span class="hljs-keyword">const</span> validate = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  e.preventDefault();
  <span class="hljs-keyword">const</span> username = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'username'</span>);
  <span class="hljs-keyword">const</span> emailAddress = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'email-address'</span>);
  <span class="hljs-keyword">if</span> (username.value === <span class="hljs-string">""</span>) {
    alert(<span class="hljs-string">"Please enter your username."</span>);
    username.focus();
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
  <span class="hljs-keyword">if</span> (emailAddress.value === <span class="hljs-string">""</span>) {
    alert(<span class="hljs-string">"Please enter your email address."</span>);
    emailAddress.focus();
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }

  <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
}

submitBtn.addEventListener(<span class="hljs-string">'click'</span>, validate);
</code></pre>
<p>But what if someone enters in random text as their email address? Currently the <code>validate</code> function will still return true. As you can imagine, sending bad data to the server can lead to problems.</p>
<p>That's where data format validation comes in.</p>
<h2 id="heading-data-format-validation">Data Format Validation</h2>
<p>This type of validation actually looks at the values in the form and verifies that they are correct.</p>
<p>Validating email addresses is notoriously difficult – there are a vast number of legitimate email addresses and hosts, and it's impossible to guess all the valid combinations of characters.</p>
<p>That said, there are a few key factors that are common in all valid email addresses: </p>
<ul>
<li>An address must contain one @ and at least one dot (.) character</li>
<li>The @ character cannot be the first character in the address</li>
<li>The . must come at least one character after the @ character</li>
</ul>
<p>With this in mind, maybe developers use regex to determine if an email address is valid or not. Here's a function that <a target="_blank" href="https://tylermcginnis.com/validate-email-address-javascript/">Tyler McGinnis recommends on his blog</a>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> emailIsValid = <span class="hljs-function"><span class="hljs-params">email</span> =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-regexp">/^[^\s@]+@[^\s@]+\.[^\s@]+$/</span>.test(email);
}

emailIsValid(<span class="hljs-string">'free@code@camp.org'</span>) <span class="hljs-comment">// false</span>
emailIsValid(<span class="hljs-string">'quincy@freecodecamp.org'</span>) <span class="hljs-comment">// true</span>
</code></pre>
<p>Added to the code from the last example, it will look like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> submitBtn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'submit-btn'</span>);

<span class="hljs-keyword">const</span> validate = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  e.preventDefault();
  <span class="hljs-keyword">const</span> username = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'username'</span>);
  <span class="hljs-keyword">const</span> emailAddress = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'email-address'</span>);
  <span class="hljs-keyword">if</span> (username.value === <span class="hljs-string">""</span>) {
    alert(<span class="hljs-string">"Please enter your username."</span>);
    username.focus();
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }

  <span class="hljs-keyword">if</span> (emailAddress.value === <span class="hljs-string">""</span>) {
    alert(<span class="hljs-string">"Please enter your email address."</span>);
    emailAddress.focus();
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }

  <span class="hljs-keyword">if</span> (!emailIsValid(emailAddress.value)) {
    alert(<span class="hljs-string">"Please enter a valid email address."</span>);
    emailAddress.focus();
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }

  <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>; <span class="hljs-comment">// Can submit the form data to the server</span>
}

<span class="hljs-keyword">const</span> emailIsValid = <span class="hljs-function"><span class="hljs-params">email</span> =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-regexp">/^[^\s@]+@[^\s@]+\.[^\s@]+$/</span>.test(email);
}

submitBtn.addEventListener(<span class="hljs-string">'click'</span>, validate);
</code></pre>
<h2 id="heading-html5-form-constraints">HTML5 Form Constraints</h2>
<p>Some of commonly used HTML5 constraints for <code>&lt;input&gt;</code> are the <code>type</code> attribute (e.g. <code>type="password"</code>), <code>maxlength</code>, <code>required</code> and <code>disabled</code>. </p>
<p>A less commonly used constraint is the <code>pattern</code> attribute that takes a JavaScript regular expression.</p>
<h2 id="heading-more-information">More Information</h2>
<ul>
<li><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation">Form Data Validation | MDN</a></li>
<li><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation">Constraint validation | MDN</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Validate Angular Template-Driven Forms ]]>
                </title>
                <description>
                    <![CDATA[ By Ankit Sharma Introduction In this article, we will learn about validations in Angular template-driven forms. We will create a simple user registration form and implement some inbuilt validations on it. Along with the inbuilt validations, we will a... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-validate-angular-template-driven-forms/</link>
                <guid isPermaLink="false">66d45dcb55db48792eed3f25</guid>
                
                    <category>
                        <![CDATA[ Angular ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Form validations ]]>
                    </category>
                
                    <category>
                        <![CDATA[ template-driven-forms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 22 Dec 2019 08:18:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9e88740569d1a4ca3da3.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ankit Sharma</p>
<h2 id="heading-introduction"><strong>Introduction</strong></h2>
<p>In this article, we will learn about validations in Angular template-driven forms. We will create a simple user registration form and implement some inbuilt validations on it. Along with the inbuilt validations, we will also implement some custom validations for the template-driven form. </p>
<p>We will consider the following custom validations for this demo:</p>
<ul>
<li>Checking for user name availability</li>
<li>Password pattern validation</li>
<li>Matching the password entered in two different fields</li>
</ul>
<p>Take a look at the application in action.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/TemplateFormValidation.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-prerequisites"><strong>Prerequisites</strong></h2>
<ul>
<li>Install Visual Studio code from <a target="_blank" href="https://code.visualstudio.com/">here</a></li>
<li>Install the latest version of Angular CLI from <a target="_blank" href="https://cli.angular.io/">here</a></li>
<li>Install the latest LTS version of Node.js from <a target="_blank" href="https://nodejs.org/en/">here</a></li>
</ul>
<h2 id="heading-source-code"><strong>Source Code</strong></h2>
<p>You can get the source code from <a target="_blank" href="https://github.com/AnkitSharma-007/angular-forms-validation">GitHub</a>.</p>
<h2 id="heading-create-the-angular-app"><strong>Create the Angular app</strong></h2>
<p>Navigate to the folder where you want to create your project file. Open a command window and run the command shown below:</p>
<pre><code>ng <span class="hljs-keyword">new</span> angular-forms-validation --routing=<span class="hljs-literal">false</span> --style=scss
</code></pre><p>We are specifying the command to create a new Angular application. The option to create the routing module is set to false and style files extension is set to SCSS. This command will create the Angular project with the name angular-forms-validation.</p>
<p>Change directories to the new project and open the project in VS Code using the set of commands below:</p>
<pre><code>cd angular-forms-validation
code .
</code></pre><h2 id="heading-install-bootstrap">Install Bootstrap</h2>
<p>Run the following command to install Bootstrap:</p>
<pre><code>npm install bootstrap --save
</code></pre><p>Add the following import definition in the <code>styles.scss</code> file:</p>
<pre><code>@<span class="hljs-keyword">import</span> <span class="hljs-string">"~bootstrap/dist/css/bootstrap.css"</span>;
</code></pre><h2 id="heading-create-the-validation-service">Create the validation service</h2>
<p>Run the following command to create a new service:</p>
<pre><code>ng g s services\customvalidation
</code></pre><p>This command will create a folder named services that has two files inside it – <code>customvalidation.service.ts</code> and <code>customvalidation.service.spec.ts</code>. Open <code>customvalidation.service.ts</code> and put the following code inside it:</p>
<pre><code><span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { ValidatorFn, AbstractControl } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;
<span class="hljs-keyword">import</span> { FormGroup } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;

@Injectable({
  <span class="hljs-attr">providedIn</span>: <span class="hljs-string">'root'</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomvalidationService</span> </span>{

  patternValidator(): ValidatorFn {
    <span class="hljs-keyword">return</span> (control: AbstractControl): { [key: string]: any } =&gt; {
      <span class="hljs-keyword">if</span> (!control.value) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
      }
      <span class="hljs-keyword">const</span> regex = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$'</span>);
      <span class="hljs-keyword">const</span> valid = regex.test(control.value);
      <span class="hljs-keyword">return</span> valid ? <span class="hljs-literal">null</span> : { <span class="hljs-attr">invalidPassword</span>: <span class="hljs-literal">true</span> };
    };
  }

  MatchPassword(password: string, <span class="hljs-attr">confirmPassword</span>: string) {
    <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">formGroup: FormGroup</span>) =&gt;</span> {
      <span class="hljs-keyword">const</span> passwordControl = formGroup.controls[password];
      <span class="hljs-keyword">const</span> confirmPasswordControl = formGroup.controls[confirmPassword];

      <span class="hljs-keyword">if</span> (!passwordControl || !confirmPasswordControl) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
      }

      <span class="hljs-keyword">if</span> (confirmPasswordControl.errors &amp;&amp; !confirmPasswordControl.errors.passwordMismatch) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
      }

      <span class="hljs-keyword">if</span> (passwordControl.value !== confirmPasswordControl.value) {
        confirmPasswordControl.setErrors({ <span class="hljs-attr">passwordMismatch</span>: <span class="hljs-literal">true</span> });
      } <span class="hljs-keyword">else</span> {
        confirmPasswordControl.setErrors(<span class="hljs-literal">null</span>);
      }
    }
  }

  userNameValidator(userControl: AbstractControl) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> {
      <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.validateUserName(userControl.value)) {
          resolve({ <span class="hljs-attr">userNameNotAvailable</span>: <span class="hljs-literal">true</span> });
        } <span class="hljs-keyword">else</span> {
          resolve(<span class="hljs-literal">null</span>);
        }
      }, <span class="hljs-number">1000</span>);
    });
  }

  validateUserName(userName: string) {
    <span class="hljs-keyword">const</span> UserList = [<span class="hljs-string">'ankit'</span>, <span class="hljs-string">'admin'</span>, <span class="hljs-string">'user'</span>, <span class="hljs-string">'superuser'</span>];
    <span class="hljs-keyword">return</span> (UserList.indexOf(userName) &gt; <span class="hljs-number">-1</span>);
  }
}
</code></pre><p>The method <code>patternValidator</code> is used to validate the password pattern in our form. The parameter for this method is of type <code>AbstractControl</code> which is a base class for the <code>FormControl</code>. </p>
<p>We will use a regular expression to validate the password. This regular expression will check for the following four conditions in the password:</p>
<ul>
<li>The password should be a minimum of eight characters long</li>
<li>It should have at least one lower case letter</li>
<li>It should have at least one upper case letter</li>
<li>It should have at least one number</li>
</ul>
<p>If the password fails the regex check, we will set the <code>invalidPassword</code> property to true.</p>
<p>The method <code>MatchPassword</code> is used to compare the passwords in two fields. This method will accept two parameters of type string. These parameters represent the name of the fields to be matched. We will get the <code>FormControl</code> for these two fields and then match the values in them. If the values do not match, we will set the <code>passwordMismatch</code> property to true.</p>
<p>The method <code>userNameValidator</code> is used to verify if the username is already taken or not. This method will accept a parameter of type <code>AbstractControl</code>. </p>
<p>We will check if the value of this field is present in a static array, UserList. If the value entered by the user is already present, we will set the <code>userNameNotAvailable</code> property to true. </p>
<p>We are using the setTimeout function to invoke this check every two seconds. This will ensure that the error will be thrown after two seconds from the time the user stops typing in the field.</p>
<p>For the sake of simplicity of this article, we are using a static array to search for the availability of user names. Ideally, it should be a service call to the server to search for the value in a database.</p>
<h2 id="heading-create-the-user-model">Create the User model</h2>
<p>Create a new folder called models inside the <code>src/app</code> folder. Add a new file called <code>user.ts</code> inside the models folder. Put the following code in the <code>user.ts</code> file.</p>
<pre><code><span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
    public name: string;
    public email: string;
    public username: string;
    public password: string;
    public confirmPassword: string;
}
</code></pre><h2 id="heading-create-custom-directives">Create custom directives</h2>
<p>We will create custom directives to implement custom validators for template-driven forms.</p>
<p>Run the command shown below to create the <code>passwordPattern</code> directive:</p>
<pre><code>ng g d directives\passwordPattern
</code></pre><p>This command will create a folder named directives that has two files inside it – <code>passwordPattern.directive.ts</code> and <code>passwordPattern.directive.spec.ts</code>. Open <code>passwordPattern.directive.ts</code> and put the following code inside it.</p>
<pre><code><span class="hljs-keyword">import</span> { Directive } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { NG_VALIDATORS, Validator, AbstractControl } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;
<span class="hljs-keyword">import</span> { CustomvalidationService } <span class="hljs-keyword">from</span> <span class="hljs-string">'../services/customvalidation.service'</span>;

@Directive({
  <span class="hljs-attr">selector</span>: <span class="hljs-string">'[appPasswordPattern]'</span>,
  <span class="hljs-attr">providers</span>: [{ <span class="hljs-attr">provide</span>: NG_VALIDATORS, <span class="hljs-attr">useExisting</span>: PasswordPatternDirective, <span class="hljs-attr">multi</span>: <span class="hljs-literal">true</span> }]
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PasswordPatternDirective</span> <span class="hljs-title">implements</span> <span class="hljs-title">Validator</span> </span>{

  <span class="hljs-keyword">constructor</span>(private customValidator: CustomvalidationService) { }

  validate(control: AbstractControl): { [key: string]: any } | <span class="hljs-literal">null</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.customValidator.patternValidator()(control);
  }
}
</code></pre><p>This directive is used to validate the password pattern. We will implement the Validator interface on the class <code>PasswordPatternDirective</code>. We will override the validate method which accepts a parameter of type <code>AbstractControl</code>, that is the control we want to validate. We will then invoke the <code>patternValidator</code> method from the service.</p>
<p>Run the command shown below to create the <code>matchPassword</code> directive:</p>
<pre><code>ng g d directives\matchPassword
</code></pre><p>Open <code>matchPassword.directive.ts</code> and put the following code inside it:</p>
<pre><code><span class="hljs-keyword">import</span> { Directive, Input } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { NG_VALIDATORS, Validator, ValidationErrors, FormGroup } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;
<span class="hljs-keyword">import</span> { CustomvalidationService } <span class="hljs-keyword">from</span> <span class="hljs-string">'../services/customvalidation.service'</span>;

@Directive({
  <span class="hljs-attr">selector</span>: <span class="hljs-string">'[appMatchPassword]'</span>,
  <span class="hljs-attr">providers</span>: [{ <span class="hljs-attr">provide</span>: NG_VALIDATORS, <span class="hljs-attr">useExisting</span>: MatchPasswordDirective, <span class="hljs-attr">multi</span>: <span class="hljs-literal">true</span> }]
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MatchPasswordDirective</span> <span class="hljs-title">implements</span> <span class="hljs-title">Validator</span> </span>{
  @Input(<span class="hljs-string">'appMatchPassword'</span>) MatchPassword: string[] = [];

  <span class="hljs-keyword">constructor</span>(private customValidator: CustomvalidationService) { }

  validate(formGroup: FormGroup): ValidationErrors {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.customValidator.MatchPassword(<span class="hljs-built_in">this</span>.MatchPassword[<span class="hljs-number">0</span>], <span class="hljs-built_in">this</span>.MatchPassword[<span class="hljs-number">1</span>])(formGroup);
  }
}
</code></pre><p>This directive is used to validate if the passwords entered in two fields are matching or not. This directive will accept an input of the type string array, which contains the fields to match. We will override the validate method and pass the parameter of type <code>FormGroup</code>. We will then invoke the <code>MatchPassword</code> method from the service. </p>
<p>Run the command shown below to create the <code>validateUserName</code> directive:</p>
<pre><code>ng g d directives\validateUserName
</code></pre><p>Open <code>validateUserName.directive.ts</code> and put the following code inside it:</p>
<pre><code><span class="hljs-keyword">import</span> { Directive, forwardRef } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { Validator, AbstractControl, NG_ASYNC_VALIDATORS } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;
<span class="hljs-keyword">import</span> { CustomvalidationService } <span class="hljs-keyword">from</span> <span class="hljs-string">'../services/customvalidation.service'</span>;
<span class="hljs-keyword">import</span> { Observable } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs'</span>;

@Directive({
  <span class="hljs-attr">selector</span>: <span class="hljs-string">'[appValidateUserName]'</span>,
  <span class="hljs-attr">providers</span>: [{ <span class="hljs-attr">provide</span>: NG_ASYNC_VALIDATORS, <span class="hljs-attr">useExisting</span>: forwardRef(<span class="hljs-function">() =&gt;</span> ValidateUserNameDirective), <span class="hljs-attr">multi</span>: <span class="hljs-literal">true</span> }]

})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ValidateUserNameDirective</span> <span class="hljs-title">implements</span> <span class="hljs-title">Validator</span> </span>{

  <span class="hljs-keyword">constructor</span>(private customValidator: CustomvalidationService) { }

  validate(control: AbstractControl): <span class="hljs-built_in">Promise</span>&lt;{ [key: string]: any }&gt; | Observable&lt;{ [key: string]: any }&gt; {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.customValidator.userNameValidator(control);
  }
}
</code></pre><p>This directive is used to validate the availability of the user name. We will override the validate method and pass the parameter of type <code>AbstractControl</code>. We will then invoke the <code>userNameValidator</code> method from the service. This method will return a promise.</p>
<h2 id="heading-create-the-template-driven-form-component">Create the template-driven form component</h2>
<p>Run the command shown below to create the template-driven-form component:</p>
<pre><code>ng g c template-driven-form
</code></pre><p>Open <code>template-driven-form.component.ts</code> and put the following code in it:</p>
<pre><code><span class="hljs-keyword">import</span> { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { User } <span class="hljs-keyword">from</span> <span class="hljs-string">'../models/user'</span>;

@Component({
  <span class="hljs-attr">selector</span>: <span class="hljs-string">'app-template-driven-form'</span>,
  <span class="hljs-attr">templateUrl</span>: <span class="hljs-string">'./template-driven-form.component.html'</span>,
  <span class="hljs-attr">styleUrls</span>: [<span class="hljs-string">'./template-driven-form.component.scss'</span>]
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TemplateDrivenFormComponent</span> </span>{

  userModal = <span class="hljs-keyword">new</span> User();

  <span class="hljs-keyword">constructor</span>() { }

  onSubmit() {
    alert(<span class="hljs-string">'Form Submitted succesfully!!!\n Check the values in browser console.'</span>);
    <span class="hljs-built_in">console</span>.table(<span class="hljs-built_in">this</span>.userModal);
  }
}
</code></pre><p>We have created an object <code>userModal</code> of type User. We will bind the form fields with the property of this object. The <code>onSubmit</code> method will show the success message on the screen and print the contents of the form to the console.</p>
<p>Open <code>template-driven-form.component.html</code> and put the following code in it:</p>
<pre><code>&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"container"</span>&gt;
    &lt;div class="row"&gt;
        &lt;div class="col-md-8 mx-auto"&gt;
            &lt;div class="card"&gt;
                &lt;div class="card-header"&gt;
                    &lt;h3&gt;Angular Template-driven Form&lt;/h3&gt;
                &lt;/div&gt;
                &lt;div class="card-body"&gt;
                    &lt;form class="form" #registerForm="ngForm" [appMatchPassword]="['password', 'confirmPassword']"
                        (ngSubmit)="registerForm.form.valid &amp;&amp; onSubmit()" novalidate&gt;
                        &lt;div class=" form-group"&gt;
                            &lt;label&gt;Name&lt;/label&gt;
                            &lt;input type="text" class="form-control" [(ngModel)]="userModal.name" name="name"
                                #name="ngModel" required&gt;
                            &lt;span class="text-danger"
                                *ngIf="(name.touched || registerForm.submitted) &amp;&amp; name.errors?.required"&gt;
                                Name is required
                            &lt;/span&gt;
                        &lt;/div&gt;
                        &lt;div class="form-group"&gt;
                            &lt;label&gt;Email&lt;/label&gt;
                            &lt;input type="text" class="form-control" [(ngModel)]="userModal.email" name="email"
                                #email="ngModel" required email&gt;
                            &lt;span class="text-danger"
                                *ngIf="(email.touched || registerForm.submitted) &amp;&amp; email.errors?.required"&gt;
                                Email is required
                            &lt;/span&gt;
                            &lt;span class="text-danger" *ngIf="email.touched &amp;&amp; email.errors?.email"&gt;
                                Enter a valid email address
                            &lt;/span&gt;
                        &lt;/div&gt;
                        &lt;div class="form-group"&gt;
                            &lt;label&gt;User Name&lt;/label&gt;
                            &lt;input type="text" class="form-control" [(ngModel)]="userModal.username" name="username"
                                #username="ngModel" appValidateUserName required&gt;
                            &lt;span class="text-danger"
                                *ngIf="(username.touched || registerForm.submitted) &amp;&amp; username.errors?.required"&gt;
                                User Name is required
                            &lt;/span&gt;
                            &lt;span class="text-danger" *ngIf="username.touched &amp;&amp; username.errors?.userNameNotAvailable"&gt;
                                User Name not available
                            &lt;/span&gt;
                        &lt;/div&gt;
                        &lt;div class="form-group"&gt;
                            &lt;label&gt;Password&lt;/label&gt;
                            &lt;input type="password" class="form-control" [(ngModel)]="userModal.password" name="password"
                                #password="ngModel" appPasswordPattern required&gt;
                            &lt;span class="text-danger"
                                *ngIf="(password.touched || registerForm.submitted) &amp;&amp; password.errors?.required"&gt;
                                Password is required
                            &lt;/span&gt;
                            &lt;span class="text-danger" *ngIf="password.touched &amp;&amp; password.errors?.invalidPassword"&gt;
                                Password should have minimum 8 characters, at least 1 uppercase letter, 1 lowercase
                                letter and 1 number
                            &lt;/span&gt;
                        &lt;/div&gt;
                        &lt;div class="form-group"&gt;
                            &lt;label&gt;Confirm Password&lt;/label&gt;
                            &lt;input type="password" class="form-control" [(ngModel)]="userModal.confirmPassword"
                                name="confirmPassword" #confirmPassword="ngModel" required&gt;
                            &lt;span class="text-danger"
                                *ngIf="(confirmPassword.touched || registerForm.submitted) &amp;&amp; confirmPassword.errors?.required"&gt;
                                Confirm Password is required
                            &lt;/span&gt;
                            &lt;span class="text-danger"
                                *ngIf="confirmPassword.touched &amp;&amp; confirmPassword.errors?.passwordMismatch"&gt;
                                Passwords doesnot match
                            &lt;/span&gt;
                        &lt;/div&gt;
                        &lt;div class="form-group"&gt;
                            &lt;button type="submit" class="btn btn-success"&gt;Register&lt;/button&gt;
                        &lt;/div&gt;
                    &lt;/form&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
</code></pre><p>We will create a template-driven form and use the Bootstrap card for styling. The card header will contain a title whereas the card body will have the form fields. </p>
<p>We will use the <code>appMatchPassword</code> directive on our form and pass the password and <code>confirmPassword</code> fields for validation. The <code>ngModel</code> property is used to bind the form control to the model. </p>
<p>For validating the user name availability we will use the <code>appValidateUserName</code> directive on the username field. Similarly, we will use the <code>appPasswordPattern</code> directive on the password field to validate the password pattern. </p>
<p>We will check for the errors in the form controls and then display the appropriate validation error message on the screen.</p>
<h2 id="heading-create-the-nav-bar-component">Create the nav-bar component</h2>
<p>Run the command shown below to create the nav-bar component:</p>
<pre><code>ng g c nav-bar
</code></pre><p>Open <code>nav-bar.component.html</code> and put the following code in it:</p>
<pre><code>&lt;nav <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"navbar navbar-expand-sm navbar-dark bg-dark fixed-top"</span>&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar-brand"</span> [<span class="hljs-attr">routerLink</span>]=<span class="hljs-string">'["/"]'</span>&gt;</span>Form Validation Demo<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"collapse navbar-collapse"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar-nav mr-auto"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"nav-item"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"nav-link"</span> [<span class="hljs-attr">routerLink</span>]=<span class="hljs-string">'["/template-form"]'</span>&gt;</span>Template Form<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
&lt;/nav&gt;
</code></pre><p>Here we are adding the navigation link to the template-driven form component.</p>
<h2 id="heading-update-the-app-component">Update the app component</h2>
<p>Open the <code>app.component.html</code> file and put the following code in it:</p>
<pre><code>&lt;app-nav-bar&gt;&lt;/app-nav-bar&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">router-outlet</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">router-outlet</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
</code></pre><h2 id="heading-update-the-app-module">Update the App module</h2>
<p>We will import the forms module and also set up the routing for our application in the app module. Add the following code in the <code>app.module.ts</code> file. You can refer to <a target="_blank" href="https://github.com/AnkitSharma-007/angular-forms-validation/blob/master/src/app/app.module.ts">GitHub</a> for the complete source code of this file:</p>
<pre><code><span class="hljs-keyword">import</span> { RouterModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/router'</span>;
<span class="hljs-keyword">import</span> { FormsModule } <span class="hljs-keyword">from</span>  <span class="hljs-string">'@angular/forms'</span>;

@NgModule({
  ...    
  imports: [
    ...
    FormsModule,
    RouterModule.forRoot([
      { <span class="hljs-attr">path</span>: <span class="hljs-string">''</span>, <span class="hljs-attr">component</span>: TemplateDrivenFormComponent },
      { <span class="hljs-attr">path</span>: <span class="hljs-string">'template-form'</span>, <span class="hljs-attr">component</span>: TemplateDrivenFormComponent }
    ]),
  ],
})
</code></pre><h2 id="heading-execution-demo">Execution demo</h2>
<p>Use the following command to start the webserver:</p>
<pre><code>ng serve -o
</code></pre><p>This command will launch the application in your default browser at <code>http://localhost:4200/</code>. You can perform all the form validations which we have discussed here. </p>
<p>This application is also hosted at <a target="_blank" href="https://ng-forms-validation.herokuapp.com/">https://ng-forms-validation.herokuapp.com/</a>. Navigate to the link and play around with it for a better understanding.</p>
<h2 id="heading-summary">Summary</h2>
<p>We have created a sample user registration form using the template-driven form approach in Angular. We have implemented the inbuilt validations as well as custom validations to the form. The Bootstrap library is used to style the form. </p>
<p>Get the source code from <a target="_blank" href="https://github.com/AnkitSharma-007/angular-forms-validation">GitHub</a> and play around with it for a better understanding.</p>
<h2 id="heading-see-also">See Also</h2>
<ul>
<li><a target="_blank" href="https://ankitsharmablogs.com/reactive-form-validation-in-angular/">Reactive Form Validation In Angular</a></li>
<li><a target="_blank" href="https://ankitsharmablogs.com/localization-in-angular-using-i18n-tools/">Localization In Angular Using i18n Tools</a></li>
<li><a target="_blank" href="https://ankitsharmablogs.com/policy-based-authorization-in-angular-using-jwt/">Policy-Based Authorization In Angular Using JWT</a></li>
<li><a target="_blank" href="https://ankitsharmablogs.com/asp-net-core-using-highcharts-with-angular-5/">ASP.NET Core – Using Highcharts With Angular 5</a></li>
<li><a target="_blank" href="https://ankitsharmablogs.com/asp-net-core-crud-using-angular-and-entity-framework-core/">ASP.NET Core – CRUD Using Angular And Entity Framework Core</a></li>
</ul>
<p>You can find this post <a target="_blank" href="https://ankitsharmablogs.com/template-driven-form-validation-in-angular/">Template-Driven Form Validation In Angular</a> and others like it on <a target="_blank" href="https://ankitsharmablogs.com/">Ankit Sharma's Blog</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Validate Angular Reactive Forms ]]>
                </title>
                <description>
                    <![CDATA[ By Ankit Sharma Introduction In this article, we will learn about validations in reactive forms in Angular. We will create a simple user registration form and implement some inbuilt validations on it. Along with the inbuilt validations, we will also ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-validate-angular-reactive-forms/</link>
                <guid isPermaLink="false">66d45dc94a7504b7409c3341</guid>
                
                    <category>
                        <![CDATA[ Angular ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Form validations ]]>
                    </category>
                
                    <category>
                        <![CDATA[ forms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 20 Dec 2019 09:24:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9e95740569d1a4ca3de6.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ankit Sharma</p>
<h2 id="heading-introduction">Introduction</h2>
<p>In this article, we will learn about validations in reactive forms in Angular. We will create a simple user registration form and implement some inbuilt validations on it. Along with the inbuilt validations, we will also implement some custom validations to the reactive form. </p>
<p>We will consider the following custom validations for this demo:</p>
<ul>
<li>Check for user name availability</li>
<li>Password pattern validation</li>
<li>Match the password entered in two different fields</li>
</ul>
<p>Take a look at the application in action.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/reactiveFormValidation.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li>Install Visual Studio code from <a target="_blank" href="https://code.visualstudio.com/">here</a></li>
<li>Install the latest version of Angular CLI from <a target="_blank" href="https://cli.angular.io/">here</a></li>
</ul>
<h2 id="heading-source-code">Source Code</h2>
<p>Get the source code from <a target="_blank" href="https://github.com/AnkitSharma-007/angular-forms-validation">GitHub</a>.</p>
<h2 id="heading-create-the-angular-app">Create the Angular app</h2>
<p>Navigate to the folder where you want to create your project file. Open a command window and run the command shown below:</p>
<pre><code>ng <span class="hljs-keyword">new</span> angular-forms-validation --routing=<span class="hljs-literal">false</span> --style=scss
</code></pre><p>We are specifying the command to create a new Angular application. The option to create the routing module is set to false and the style files extension is set to <code>scss</code>. This command will create the Angular project with the name <code>angular-forms-validation</code>.</p>
<p>Change directories to the new project and open the project in VS Code using the set of command shown below:</p>
<pre><code>cd angular-forms-validation 
code .
</code></pre><h2 id="heading-install-bootstrap">Install Bootstrap</h2>
<p>Run the following command to install the Bootstrap library:</p>
<pre><code>npm install bootstrap --save
</code></pre><p>Add the following import definition in the <code>styles.scss</code> file:</p>
<pre><code>@<span class="hljs-keyword">import</span> <span class="hljs-string">"~bootstrap/dist/css/bootstrap.css"</span>;
</code></pre><h2 id="heading-create-the-validation-service">Create the validation service</h2>
<p>Run the following command to create a new service:</p>
<pre><code>ng g s services\customvalidation
</code></pre><p>This command will create a folder named services that has two files in it – <code>customvalidation.service.ts</code> and <code>customvalidation.service.spec.ts</code>. Open the <code>customvalidation.service.ts</code> file and put the following code in it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { ValidatorFn, AbstractControl } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;
<span class="hljs-keyword">import</span> { FormGroup } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;

@Injectable({
  <span class="hljs-attr">providedIn</span>: <span class="hljs-string">'root'</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomvalidationService</span> </span>{

  patternValidator(): ValidatorFn {
    <span class="hljs-keyword">return</span> (control: AbstractControl): { [key: string]: any } =&gt; {
      <span class="hljs-keyword">if</span> (!control.value) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
      }
      <span class="hljs-keyword">const</span> regex = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$'</span>);
      <span class="hljs-keyword">const</span> valid = regex.test(control.value);
      <span class="hljs-keyword">return</span> valid ? <span class="hljs-literal">null</span> : { <span class="hljs-attr">invalidPassword</span>: <span class="hljs-literal">true</span> };
    };
  }

  MatchPassword(password: string, <span class="hljs-attr">confirmPassword</span>: string) {
    <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">formGroup: FormGroup</span>) =&gt;</span> {
      <span class="hljs-keyword">const</span> passwordControl = formGroup.controls[password];
      <span class="hljs-keyword">const</span> confirmPasswordControl = formGroup.controls[confirmPassword];

      <span class="hljs-keyword">if</span> (!passwordControl || !confirmPasswordControl) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
      }

      <span class="hljs-keyword">if</span> (confirmPasswordControl.errors &amp;&amp; !confirmPasswordControl.errors.passwordMismatch) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
      }

      <span class="hljs-keyword">if</span> (passwordControl.value !== confirmPasswordControl.value) {
        confirmPasswordControl.setErrors({ <span class="hljs-attr">passwordMismatch</span>: <span class="hljs-literal">true</span> });
      } <span class="hljs-keyword">else</span> {
        confirmPasswordControl.setErrors(<span class="hljs-literal">null</span>);
      }
    }
  }

  userNameValidator(userControl: AbstractControl) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> {
      <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.validateUserName(userControl.value)) {
          resolve({ <span class="hljs-attr">userNameNotAvailable</span>: <span class="hljs-literal">true</span> });
        } <span class="hljs-keyword">else</span> {
          resolve(<span class="hljs-literal">null</span>);
        }
      }, <span class="hljs-number">1000</span>);
    });
  }

  validateUserName(userName: string) {
    <span class="hljs-keyword">const</span> UserList = [<span class="hljs-string">'ankit'</span>, <span class="hljs-string">'admin'</span>, <span class="hljs-string">'user'</span>, <span class="hljs-string">'superuser'</span>];
    <span class="hljs-keyword">return</span> (UserList.indexOf(userName) &gt; <span class="hljs-number">-1</span>);
  }
}
</code></pre>
<p>The method <code>patternValidator</code> is used to validate the password pattern in our form. The parameter for this method is of type <code>AbstractControl</code> which is a base class for the <code>FormControl</code>. </p>
<p>We will use a regular expression to validate the password. We will validate the following four conditions using the regular expression:</p>
<ul>
<li>The password should be a minimum of eight characters long.</li>
<li>It has at least one lower case letter.</li>
<li>It has at least one upper case letter.</li>
<li>It has at least one number.</li>
</ul>
<p>If the password fails the regex check, we will set the <code>invalidPassword</code> property to true.</p>
<p>The method <code>MatchPassword</code> is used to compare the passwords in two fields. This method will accept two parameters of type string. These parameters represent the name of the fields to be matched. We will get the <code>FormControl</code> for these two fields and then match the values in them. If the values do not match, we will set the <code>passwordMismatch</code> property to true.</p>
<p>The method <code>userNameValidator</code> is used to verify whether the username is already taken or not. This method will accept a parameter of type <code>AbstractControl</code>. We will check if the value of this field is present in a static array, <code>UserList</code>. If the value entered by the user is already present, we will set the <code>userNameNotAvailable</code> property to true. </p>
<p>We are using the <code>setTimeout</code> function to invoke this check every two seconds. This will ensure that the error will be thrown after two seconds from the time the user stops typing in the field.</p>
<blockquote>
<p>For the sake of simplicity of this article, we are using a static array to search for the availability of user names. Ideally, it should be a service call to the server to search the value in a database.</p>
</blockquote>
<h2 id="heading-create-the-reactive-form-component">Create the reactive form component</h2>
<p>Run the following command to create the reactive-form component:</p>
<pre><code>ng g c reactive-form
</code></pre><p>Open <code>reactive-form.component.ts</code> and put the following code in it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { Component, OnInit } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { Validators, FormGroup, FormBuilder } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;
<span class="hljs-keyword">import</span> { CustomvalidationService } <span class="hljs-keyword">from</span> <span class="hljs-string">'../services/customvalidation.service'</span>;

@Component({
  <span class="hljs-attr">selector</span>: <span class="hljs-string">'app-reactive-form'</span>,
  <span class="hljs-attr">templateUrl</span>: <span class="hljs-string">'./reactive-form.component.html'</span>,
  <span class="hljs-attr">styleUrls</span>: [<span class="hljs-string">'./reactive-form.component.scss'</span>]
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ReactiveFormComponent</span> <span class="hljs-title">implements</span> <span class="hljs-title">OnInit</span> </span>{

  <span class="hljs-attr">registerForm</span>: FormGroup;
  submitted = <span class="hljs-literal">false</span>;

  <span class="hljs-keyword">constructor</span>(
    private fb: FormBuilder,
    private customValidator: CustomvalidationService
  ) { }

  ngOnInit() {
    <span class="hljs-built_in">this</span>.registerForm = <span class="hljs-built_in">this</span>.fb.group({
      <span class="hljs-attr">name</span>: [<span class="hljs-string">''</span>, Validators.required],
      <span class="hljs-attr">email</span>: [<span class="hljs-string">''</span>, [Validators.required, Validators.email]],
      <span class="hljs-attr">username</span>: [<span class="hljs-string">''</span>, [Validators.required], <span class="hljs-built_in">this</span>.customValidator.userNameValidator.bind(<span class="hljs-built_in">this</span>.customValidator)],
      <span class="hljs-attr">password</span>: [<span class="hljs-string">''</span>, Validators.compose([Validators.required, <span class="hljs-built_in">this</span>.customValidator.patternValidator()])],
      <span class="hljs-attr">confirmPassword</span>: [<span class="hljs-string">''</span>, [Validators.required]],
    },
      {
        <span class="hljs-attr">validator</span>: <span class="hljs-built_in">this</span>.customValidator.MatchPassword(<span class="hljs-string">'password'</span>, <span class="hljs-string">'confirmPassword'</span>),
      }
    );
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">registerFormControl</span>() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.registerForm.controls;
  }

  onSubmit() {
    <span class="hljs-built_in">this</span>.submitted = <span class="hljs-literal">true</span>;
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.registerForm.valid) {
      alert(<span class="hljs-string">'Form Submitted succesfully!!!\n Check the values in browser console.'</span>);
      <span class="hljs-built_in">console</span>.table(<span class="hljs-built_in">this</span>.registerForm.value);
    }
  }
}
</code></pre>
<p>We will create a variable <code>registerForm</code> of type <code>FormGroup</code>. In the <code>ngOnInit</code> method, we will set the controls for the form using the <code>FormBuilder</code> class. All the fields are set as a required field for this form. We will invoke the <code>userNameValidator</code> method of the service using the bind function. </p>
<p>For the password field, we will use the compose method to merge in multiple validators into a single function. We will also invoke the <code>MatchPassword</code> method and pass the name of the <code>password</code> and <code>confirmPassword</code> form controls as parameters.</p>
<p>The <code>registerFormControl</code> property will return the form controls of the form. The <code>onSubmit</code> method will print the content of the form on the console if the form is valid and submitted successfully.</p>
<p>Open <code>reactive-form.component.html</code> and put the following code in it:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"row"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col-md-8 mx-auto"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card-header"</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Angular Reactive Form<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card-body"</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form"</span> [<span class="hljs-attr">formGroup</span>]=<span class="hljs-string">"registerForm"</span> (<span class="hljs-attr">ngSubmit</span>)=<span class="hljs-string">"onSubmit()"</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span> <span class="hljs-attr">formControlName</span>=<span class="hljs-string">"name"</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-danger"</span>
                                *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"(registerFormControl.name.touched || submitted) &amp;&amp; registerFormControl.name.errors?.required"</span>&gt;</span>
                                Name is required
                            <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Email<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span> <span class="hljs-attr">formControlName</span>=<span class="hljs-string">"email"</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-danger"</span>
                                *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"(registerFormControl.email.touched || submitted) &amp;&amp; registerFormControl.email.errors?.required"</span>&gt;</span>
                                Email is required
                            <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-danger"</span>
                                *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"registerFormControl.email.touched &amp;&amp; registerFormControl.email.errors?.email"</span>&gt;</span>
                                Enter a valid email address
                            <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>User Name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span> <span class="hljs-attr">formControlName</span>=<span class="hljs-string">"username"</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-danger"</span>
                                *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"(registerFormControl.username.touched || submitted) &amp;&amp; registerFormControl.username.errors?.required"</span>&gt;</span>
                                User Name is required
                            <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-danger"</span>
                                *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"registerFormControl.username.touched &amp;&amp; registerFormControl.username.errors?.userNameNotAvailable"</span>&gt;</span>
                                User Name is not available
                            <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Password<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span> <span class="hljs-attr">formControlName</span>=<span class="hljs-string">"password"</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-danger"</span>
                                *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"(registerFormControl.password.touched || submitted) &amp;&amp; registerFormControl.password.errors?.required"</span>&gt;</span>
                                Password is required
                            <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-danger"</span>
                                *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"registerFormControl.password.touched &amp;&amp; registerFormControl.password.errors?.invalidPassword"</span>&gt;</span>
                                Password should have minimum 8 characters, at least 1 uppercase letter, 1 lowercase
                                letter and 1 number
                            <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Confirm Password<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span> <span class="hljs-attr">formControlName</span>=<span class="hljs-string">"confirmPassword"</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-danger"</span>
                                *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"(registerFormControl.confirmPassword.touched || submitted)&amp;&amp; registerFormControl.confirmPassword.errors?.required"</span>&gt;</span>
                                Confirm Password is required
                            <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-danger"</span>
                                *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"registerFormControl.confirmPassword.touched &amp;&amp; registerFormControl.confirmPassword.errors?.passwordMismatch"</span>&gt;</span>
                                Passwords doesnot match
                            <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-success"</span>&gt;</span>Register<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>We will create a reactive form and use the Bootstrap card for styling. The card header will contain a title whereas the card body will have the form fields. We will bind the <code>formGroup</code> property of the <code>&lt;form&gt;</code> tag to the name of our form which is <code>registerForm</code>. The <code>onSubmit</code> method will be invoked on submitting the form. We will also bind the <code>formControlName</code> property of each input field to the control name of our <code>FormGroup</code>. We will check for errors in the form controls and then display the appropriate validation error message on the screen.</p>
<h2 id="heading-create-the-nav-bar-component">Create the nav-bar component</h2>
<p>Run the following command to create the nav-bar component:</p>
<pre><code>ng g c nav-bar
</code></pre><p>Open <code>nav-bar.component.html</code> and put the following code in it:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">nav</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar navbar-expand-sm navbar-dark bg-dark fixed-top"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar-brand"</span> [<span class="hljs-attr">routerLink</span>]=<span class="hljs-string">'["/"]'</span>&gt;</span>Form Validation Demo<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"collapse navbar-collapse"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar-nav mr-auto"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"nav-item"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"nav-link"</span> [<span class="hljs-attr">routerLink</span>]=<span class="hljs-string">'["/reactive-form"]'</span>&gt;</span>Reactive Form<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span>
</code></pre>
<p>We are adding the navigation link to the reactive form component in the nav bar.</p>
<h2 id="heading-update-the-app-component">Update the app component</h2>
<p>Open the <code>app.component.html</code> file and put the following code in it:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">app-nav-bar</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">app-nav-bar</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">router-outlet</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">router-outlet</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h2 id="heading-update-the-app-module">Update the App module</h2>
<p>Add the following code in the <code>app.module.ts</code> file. We will import the forms module and define the routing for our application. You can refer to <a target="_blank" href="https://github.com/AnkitSharma-007/angular-forms-validation/blob/master/src/app/app.module.ts">GitHub</a> for the complete source code of this file.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { RouterModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/router'</span>;
<span class="hljs-keyword">import</span> { ReactiveFormsModule } <span class="hljs-keyword">from</span>  <span class="hljs-string">'@angular/forms'</span>;

@NgModule({
  ...    
  imports: [
    ...
    ReactiveFormsModule,
    RouterModule.forRoot([
      { <span class="hljs-attr">path</span>: <span class="hljs-string">''</span>, <span class="hljs-attr">component</span>: ReactiveFormComponent },
      { <span class="hljs-attr">path</span>: <span class="hljs-string">'reactive-form'</span>, <span class="hljs-attr">component</span>: ReactiveFormComponent }
    ]),
  ],
})
</code></pre>
<h2 id="heading-execution-demo">Execution demo</h2>
<p>We will use the following command to start the web server:</p>
<pre><code>ng serve -o
</code></pre><p>This command will launch the application in your default browser at <code>http://localhost:4200/</code>. You can perform all the form validations which we have discussed here. </p>
<p>This application is also hosted at <a target="_blank" href="https://ng-forms-validation.herokuapp.com/">https://ng-forms-validation.herokuapp.com/</a>. Navigate to the link and play around with it for a better understanding.</p>
<h2 id="heading-summary">Summary</h2>
<p>We have created a sample user registration form using the reactive form approach in Angular. We have implemented the inbuilt validations as well as custom validations to the form. The Bootstrap library is used to style the form. </p>
<p>Get the source code from <a target="_blank" href="https://github.com/AnkitSharma-007/angular-forms-validation">GitHub</a> and play around with it for a better understanding.</p>
<h2 id="heading-see-also">See Also</h2>
<ul>
<li><a target="_blank" href="https://ankitsharmablogs.com/localization-in-angular-using-i18n-tools/">Localization In Angular Using i18n Tools</a></li>
<li><a target="_blank" href="https://ankitsharmablogs.com/template-driven-form-validation-in-angular/">Template-Driven Form Validation In Angular</a></li>
<li><a target="_blank" href="https://ankitsharmablogs.com/understanding-angular-animation/">Understanding Angular Animation</a></li>
<li><a target="_blank" href="https://ankitsharmablogs.com/policy-based-authorization-in-angular-using-jwt/">Policy-Based Authorization In Angular Using JWT</a></li>
<li><a target="_blank" href="https://ankitsharmablogs.com/facebook-authentication-and-authorization-in-server-side-blazor-app/">Facebook Authentication And Authorization In Server-Side Blazor App</a></li>
</ul>
<p>You can find other posts like <a target="_blank" href="https://ankitsharmablogs.com/reactive-form-validation-in-angular/">Reactive Form Validation in Angular</a> on <a target="_blank" href="https://ankitsharmablogs.com/">Ankit Sharma's Blog</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
