{"id":179,"date":"2012-02-13T22:02:26","date_gmt":"2012-02-13T14:02:26","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=179"},"modified":"2018-09-03T21:33:02","modified_gmt":"2018-09-03T13:33:02","slug":"how-to-validate-input-fields-as-the-user-is-filling-up-a-form-with-jquery","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-validate-input-fields-as-the-user-is-filling-up-a-form-with-jquery\/","title":{"rendered":"How to validate input fields as the user is filling up a form with jQuery"},"content":{"rendered":"<p>In order to get sensible data from users via an online form, we have to validate data that we receive from them . As much as possible, we will want the data validation process to minimize frustration to our users. <\/p>\n<p>We could have perform the data validation on the input fields at the point when the form is submitted. However, a better way will be to perform data validation on the input fields as the user is filling up the form.   The validation process can follow such a sequence: <\/p>\n<ol>\n<li>User clicks on the input field.<\/li>\n<li>User fills up the input field with data.<\/li>\n<li>User clicks away from the input field.<\/li>\n<li><strong>Data validation occurs on the input field.<\/strong> If there are any errors, display the error message near to the input field. Else everything proceeds as usual.<\/li>\n<\/ol>\n<h3>The demo scenario<\/h3>\n<p>For the sake of simplicity, I will illustrate this effect with two input text field. The first input text field requires a number from the user while the second one is optional. There are two error scenarios for the mandatory input:<\/p>\n<ol>\n<li>Nothing is entered. User had previously entered some correct data and for some reason, removing the data from the text field.<\/li>\n<li>User entered non numeric data in the input field.<\/li>\n<\/ol>\n<h4>The HTML code for the form<\/h4>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\n&lt;form action=&quot;#&quot; method=&quot;post&quot;&gt;\r\n    &lt;fieldset&gt;\r\n\t&lt;label for=&quot;yourNumberTextField&quot;&gt;Your number:&lt;\/label&gt;\r\n\t&lt;input type=&quot;text&quot; id=&quot;yourNumberTextField&quot;\/&gt;\r\n    &lt;\/fieldset&gt;\r\n    &lt;fieldset&gt;\r\n\t&lt;label for=&quot;optionalTextField&quot;&gt;Optional value:&lt;\/label&gt;\r\n\t&lt;input type=&quot;text&quot; id=&quot;optionalTextField&quot;\/&gt;\r\n    &lt;\/fieldset&gt;\r\n&lt;\/form&gt;\r\n<\/pre>\n<p>The HTML form is simple - Two labels and two text input fields. To facilitate DOM selection using jQuery, I had given the number input field a unique ID \"yourNumberTextField\".<\/p>\n<h4>CSS rules for our form<\/h4>\n<pre class=\"brush: css; title: ; notranslate\" title=\"\">\r\ninput&#x5B;type=text] + p {\r\n    display: inline;\r\n    margin-left: 5px;\r\n}\r\n\r\n.errorField {\r\n    border: 1px solid red;\r\n}\r\n\r\n.errorMessage {\r\n    color: red;\r\n}\r\n<\/pre>\n<p>The first rule make paragraphs appear right after our input field, instead of beneath it. In this demo, I had chosen to enclose error messages with the <strong>&lt;p&gt;<\/strong> tag.<\/p>\n<p>The second rule will highlight the input field with red borders when data validation fails.<\/p>\n<p>The third one will make the error message appear in red text.<\/p>\n<h4>Data validation logic<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n$(document).ready(\r\n    \/\/ Handler for document ready event\r\n    function () {\r\n        $('#yourNumberTextField').change(\r\n            \/\/ Handler for changes detected on yourNumberTextField\r\n            function () {\r\n                \/\/ Add a change listener to yourNumberTextField\r\n                if ($.trim( $(this).attr('value') ) == '') {\r\n                    outputErrorMessage($(this), \r\n                        '&lt;p class=&quot;errorMessage&quot;&gt;Please fill in a number.&lt;\/p&gt;');\r\n                }\r\n                else if (!$.isNumeric($.trim($(this).attr('value')))) {\r\n                    outputErrorMessage($(this), \r\n                        '&lt;p class=&quot;errorMessage&quot;&gt;Your input should be a number.&lt;\/p&gt;');\r\n                }\r\n                else {\r\n                    $(this).removeClass('errorField');\r\n                    $(this).next().remove();\r\n                }\r\n            } \/\/ end function()\r\n        ); \/\/ end $('#yourNumberTextField').change\r\n    } \/\/ end function\r\n); \/\/ end function $(document).ready\r\n<\/pre>\n<p>First of all, I <a href=\"http:\/\/docs.jquery.com\/How_jQuery_Works#Launching_Code_on_Document_Ready\" title=\"jQuery reference for launching code on document ready\" target=\"_blank\">add a document ready handler<\/a> to ensure that I add the change handler to the input field only when it is ready to be manipulated. <\/p>\n<p>Inside the document ready handler, I <a href=\"http:\/\/api.jquery.com\/change\/\" title=\"jQuery reference for .change\" target=\"_blank\">add a change handler<\/a> to the text input field - <code>#yourNumberTextField<\/code>.  <\/p>\n<p>Finally inside the change handler, I include the data validation logic. <\/p>\n<p><code><strong>$(this)<a href=\"http:\/\/api.jquery.com\/attr\/\" title=\"jQuery reference for .attr\" target=\"_blank\">.attr<\/a>('value')<\/strong><\/code> returns the new value in the input field. With this new value, the first if statement checks for emptiness while the second checks for non numeric values. When these two conditions hold true, I delegate the output of error messages to the <code><strong>outputErrorMessage<\/strong><\/code> function (discussed in the next section). <\/p>\n<p>When the input is correct, the else statement will run. Inside the else statement block, <code><strong>$(this)<a href=\"http:\/\/api.jquery.com\/removeClass\/\" title=\"jQuery reference for .removeClass\" target=\"_blank\">.removeClass<\/a>('errorField')<\/strong><\/code> removes the errorField css rule which may had been applied on the input field. <code><strong>$(this)<a href=\"http:\/\/api.jquery.com\/next\/\" title=\"jQuery reference for .next\" target=\"_blank\">.next<\/a>()<a href=\"http:\/\/api.jquery.com\/remove\/\" title=\"jQuery reference for .remove\" target=\"_blank\">.remove<\/a>()<\/strong><\/code> then removes any error message which may had been added next to the input field.<\/p>\n<h4>Display an error message beside the input field<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nfunction outputErrorMessage($inputField, errorMessage) {\r\n    \/\/ If there is a previous message\r\n    if (!$inputField.next().length == 0) {\r\n        \/\/ Remove the previous message\r\n        $inputField.next().remove();\r\n    } \/\/ end if\r\n    \r\n    \/\/ Show the error message\r\n    $inputField.after(errorMessage);\r\n    \/\/ 'Highlight' the field\r\n    $inputField.addClass('errorField');\r\n    $inputField.focus();\r\n} \/\/ end function outputErrorMessage($inputField, errorMessage)\r\n<\/pre>\n<p>The if statement checks for any previous error message that may had been added next to the input field. In such a case, <code><strong>$inputField<a href=\"http:\/\/api.jquery.com\/next\" title=\"jQuery reference for .next\" target=\"_blank\">.next<\/a>().<a href=\"http:\/\/api.jquery.com\/remove\" title=\"jQuery reference for .remove\" target=\"_blank\">remove<\/a>()<\/strong><\/code>. The remaining statements then shows the error message, highlights and brings focus to the input field. <\/p>\n<h3>Try the demo form<\/h3>\n<div class=\"callToAction\">\n<a href=\"http:\/\/www.techcoil.com\/proof-of-concepts\/jquery-validate-field-on-change\" class=\"readMoreLink\">See this proof of concept<\/a>\n<\/div>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-2T\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-2T&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-2T&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F179&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>In order to get sensible data from users via an online form, we have to validate data that we receive from them . As much as possible, we will want the data validation process to minimize frustration to our users. <\/p>\n<p>We could have perform the data validation on the input fields at the point when the form is submitted. However, a better way will be to perform data validation on the input fields as the user is filling up the form.   The validation process can follow such a sequence: <\/p>\n<ol>\n<li>User clicks on the input field.<\/li>\n<li>User fills up the input field with data.<\/li>\n<li>User clicks away from the input field.<\/li>\n<li><strong>Data validation occurs on the input field.<\/strong> If there are any errors, display the error message near to the input field. Else everything proceeds as usual.<\/li>\n<\/ol>\n","protected":false},"author":1,"featured_media":1208,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[92,90,89],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/jquery-logo-mark-dark.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-2T","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/179"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=179"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/179\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1208"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=179"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=179"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=179"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}