{"id":329,"date":"2013-10-13T15:57:22","date_gmt":"2013-10-13T07:57:22","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=329"},"modified":"2018-09-09T12:57:06","modified_gmt":"2018-09-09T04:57:06","slug":"how-to-use-jquery-to-intercept-form-submissions-and-validate-form-input","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-use-jquery-to-intercept-form-submissions-and-validate-form-input\/","title":{"rendered":"How to use jQuery to intercept form submissions and validate form input"},"content":{"rendered":"<p>There came a time where I had to create a HTML form to accept inputs from users in order to generate a report. Before submitting the form to the back end server, there are some validations that I can perform on the data at the client side to reduce the number of HTTP responses that my server had to generate for unwanted inputs. The cost savings is especially significant when the form submission <a href=\"http:\/\/www.techcoil.com\/blog\/uploading-large-http-multipart-request-with-system-net-httpwebrequest-in-c\/\" title=\"Uploading large HTTP multipart request with System.Net.HttpWebRequest in C#\" target=\"_blank\">contains large file as part of the HTTP request<\/a>.<\/p>\n<p>I chose to use jQuery for intercepting the form submissions and do some data validation before I allow the browser to create a HTTP request to the server. This post documents a proof of concept, as a stepping stone, to realize my objective.<\/p>\n<h2>The sample scenario<\/h2 >\nI have a form that asks the user for a number via a text field. When the user clicks on the submit button, jQuery will help me intercept the form submission and check whether the data submitted by the user is a numeric value. If data submitted by user is not numeric, the codes will stop the form submission and prompt a message. <\/p>\n<h2>JavaScript to intercept form submission and validate the data from the user<\/h2>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n$(document).ready(\r\n\tfunction () {\t\r\n\t\t$('#numberInputForm').submit(\t\r\n\t\t\tfunction(event) {\r\n\t\t\t\tvar numberTextFieldVal = $('#numberTextField').val();\r\n\t\t\t\tif (isNaN(numberTextFieldVal) || numberTextFieldVal == '') {\r\n\t\t\t\t\twriteMessageToWebPage(&quot;Data submitted is not a number!&quot;);\r\n\t\t\t\t\tevent.preventDefault();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t);\r\n\t}\r\n); \r\n<\/pre>\n<p>When the HTML document is ready, I attach a callback function for <code>jQuery<\/code> to notify me when there is a form submission triggered from the form with <code>numberInputForm<\/code> as the id. The callback function accepts a event object which can be used to stop the form submission later.<\/p>\n<p>I then get the value of the text field with <code>numberTextField<\/code> as the id. Using the <code>isNaN<\/code> function, I check if the value from the text field is not a number of if it is an empty string. If the value from the text field is not a number, I call the function <code>writeMessageToWebPage<\/code>:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nfunction writeMessageToWebPage(msg) {\r\n\t$('#feedbackMsg').html(msg);\t\r\n}\r\n<\/pre>\n<p>and call <code>event.preventDefault<\/code> to stop the form submission. The <code>writeMessageToWebPage<\/code> function receives a message from its input parameter and set it as the HTML contents to the HTML element with <code>feedbackMsg<\/code> as the id.<\/p>\n<h2>The php codes that realized the HTML form<\/h2>\n<p>Referring to <a href=\"http:\/\/www.techcoil.com\/blog\/code-segments-for-rendering-html-4-0-pages\/\" title=\"Code segments for rendering html 4.0 pages\" target=\"_blank\">the HTML reference that I had created earlier<\/a>, I created a php script to generate the HTML codes for this proof of concept.<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;html&gt;\r\n\t&lt;head&gt;\r\n\t&lt;script type=&quot;text\/javascript&quot; src=&quot;http:\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1.7.1\/jquery.min.js&quot;&gt;&lt;\/script&gt;\r\n\t&lt;script type=&quot;text\/javascript&quot;&gt;\r\n\t\r\n\tfunction writeMessageToWebPage(msg) {\r\n\t\t\r\n\t\t$('#feedbackMsg').html(msg);\r\n\t\t\r\n\t}\r\n\t\r\n\t$(document).ready(\r\n\t\t\r\n\t\tfunction () {\r\n\t\t\t\r\n\t\t\t$('#numberInputForm').submit(\r\n\t\t\t\t\r\n\t\t\t\tfunction(event) {\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar numberTextFieldVal = $('#numberTextField').val();\r\n\t\t\t\t\tif (isNaN(numberTextFieldVal) || numberTextFieldVal == '') {\r\n\t\t\t\t\t\twriteMessageToWebPage(&quot;Data submitted is not a number!&quot;);\r\n\t\t\t\t\t\tevent.preventDefault();\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t);\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t); \r\n\t\r\n\t&lt;\/script&gt;\r\n\t&lt;\/head&gt;\r\n\t&lt;body&gt;\r\n\t\t&lt;div id=&quot;feedbackMsg&quot;&gt;\r\n&lt;?php\r\n\t\t\tif (isset($_POST&#x5B;'numberTextField'])) {\r\n\t\t\t\techo 'You had just submitted the number: ' . $_POST&#x5B;'numberTextField'];\r\n\t\t\t}\r\n?&gt;\t\t\t\r\n\t\t&lt;\/div&gt;\r\n\t\t&lt;form id=&quot;numberInputForm&quot; method=&quot;post&quot; action=&quot;&lt;?php echo $_SERVER&#x5B;'REQUEST_URI'];?&gt;&quot;&gt;\r\n\t\t&lt;fieldset&gt;\r\n\t\t\t&lt;label for=&quot;numberTextField&quot;&gt;Number:&lt;\/label&gt;\r\n\t\t\t&lt;input id=&quot;numberTextField&quot; name=&quot;numberTextField&quot; type=&quot;text&quot;\/&gt;\r\n\t\t&lt;\/fieldset&gt;\r\n\t\t&lt;fieldset&gt;\r\n\t\t\t&lt;input name=&quot;submitButton&quot; type=&quot;submit&quot; value=&quot;submit&quot;\/&gt;\r\n\t\t&lt;\/fieldset&gt;\r\n\t\t&lt;\/form&gt;\r\n\t&lt;\/body&gt;\r\n&lt;\/html&gt;\r\n<\/pre>\n<p>When a form submission is allowed, the browser will post the HTTP request to the same script that renders the form. The script checks if there is post data that is tagged with <code>numberTextField<\/code>. If there is, it displays the value back to the user.<\/p>\n<div class=\"callToAction\">\n   <a target=\"_blank\" href=\"http:\/\/www.techcoil.com\/proof-of-concepts\/using-jQuery-to-intercept-form-submissions-and-validate-form-input\" class=\"readMoreLink\">See how this proof of concept works<\/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-5j\" 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-5j&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-5j&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%2F329&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>There came a time where I had to create a HTML form to accept inputs from users in order to generate a report. Before submitting the form to the back end server, there are some validations that I can perform on the data at the client side to reduce the number of HTTP responses that my server had to generate for unwanted inputs. The cost savings is especially significant when the form submission <a href=\"http:\/\/www.techcoil.com\/blog\/uploading-large-http-multipart-request-with-system-net-httpwebrequest-in-c\/\" title=\"Uploading large HTTP multipart request with System.Net.HttpWebRequest in C#\" target=\"_blank\">contains large file as part of the HTTP request<\/a>.<\/p>\n<p>I chose to use jQuery for intercepting the form submissions and do some data validation before I allow the browser to create a HTTP request to the server. This post documents a proof of concept, as a stepping stone, to realize my objective.<\/p>\n","protected":false},"author":1,"featured_media":1208,"comment_status":"closed","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":[90,16,175,89],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/jquery-logo-mark-dark.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-5j","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/329"}],"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=329"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/329\/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=329"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=329"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=329"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}