{"id":2242,"date":"2019-12-23T16:29:31","date_gmt":"2019-12-23T16:29:31","guid":{"rendered":"https:\/\/mindfusion.eu\/blog\/?p=2242"},"modified":"2021-01-25T16:07:27","modified_gmt":"2021-01-25T16:07:27","slug":"multi-tabs-form-in-javascript-with-validation","status":"publish","type":"post","link":"https:\/\/mindfusion.dev\/blog\/multi-tabs-form-in-javascript-with-validation\/","title":{"rendered":"Multi-tabs Form in JavaScript with Validation"},"content":{"rendered":"<p>In this blog post we will create a form that spans over several tabs. Each tab contains input fields for a specific type of information. There are placeholders and restrictions for each input field. If the provided data is not correct we display a guiding message and select the first tab that has wrong data. All incorrect fields are outlined with red.<\/p>\n<p><a title=\"JavaScript Tab Forms\" href=\"https:\/\/mindfusion.dev\/javascript-demo.html?sample=TabForm\"><img decoding=\"async\" title=\"MindFusion JavaScript Tabs Control\" src=\"https:\/\/mindfusion.dev\/samples\/javascript\/ui\/tabs_form_errors.png\" \/><\/a><\/p>\n<h2>I. General Settings<\/h2>\n<p>We will use two files for our form &#8211; one is a web page and the other a JavaScript file that will hold all JavaScript code for the sample. They both are names TabForm.<\/p>\n<p>In the web page we add references to the css file that holds the theme we&#8217;ve chosen:<\/p>\n<pre id=\"line1\">&lt;<span class=\"start-tag\">link<\/span> <span class=\"attribute-name\">rel<\/span>=\"<a class=\"attribute-value\">stylesheet<\/a>\" <span class=\"attribute-name\">type<\/span>=\"<a class=\"attribute-value\">text\/css<\/a>\" <span class=\"attribute-name\">href<\/span>=\"<a class=\"attribute-value\" href=\"view-source:https:\/\/mindfusion.dev\/blog\/multi-tabs-form-in-javascript-with-validation\/themes\/light.css\">themes\/light.css<\/a>\"&gt;<\/pre>\n<p>This is the CSS for the light theme of the MindFusion JavaScript UI controls. There are various themes provided out-of-the-box with the library and you can choose another one.<\/p>\n<p>Then, at the bottom of the web page, before the closing BODY tag we add references to the three JavaScript files that we want to use:<\/p>\n<pre id=\"line1\">&lt;<span class=\"start-tag\">div<\/span> <span class=\"attribute-name\">style<\/span>=\"<a class=\"attribute-value\">position: absolute; top: 0px; left: 0; right: 0; bottom: 0;<\/a>\"&gt;\n<span id=\"line332\"><\/span>    &lt;<span class=\"start-tag\">div<\/span> <span class=\"attribute-name\">id<\/span>=\"<a class=\"attribute-value\">host<\/a>\"&gt;\n<span id=\"line337\"><\/span>    &lt;\/<span class=\"end-tag\">div<\/span>&gt;\n<span id=\"line338\"><\/span>&lt;\/<span class=\"end-tag\">div<\/span>&gt;<\/pre>\n<p>The first two of them point to the libraries of the UI controls: MindFusion.Common and MindFusion.UI. The other is a reference to the JS code-behind file.<\/p>\n<p>In order to render the <a title=\"MindFusion UI for JavaScript: TabControl\" href=\"https:\/\/www.mindfusion.dev\/onlinehelp\/javascript.pack\/index.htm?T_MindFusion_UI_TabControl.htm\">TabControl<\/a> we need a DIV element. So, we create one and give it an id &#8211; that is important:<\/p>\n<div style=\"position: absolute; top: 0px; left: 0; right: 0; bottom: 0;\">\n<div id=\"host\"><\/div>\n<\/div>\n<p>We also add a paragraph with an id and red stroke &#8211; it will render text, that describes the error fields and the validation message for each one &#8211; if the user has provided wrong data.<\/p>\n<h2>II. Creating the Tab Control and the Tab Pages<\/h2>\n<p>In the code-behind file we first add mappings to the two namespaces we want to use:<\/p>\n<pre>var ui = MindFusion.UI;\nvar d = MindFusion.Drawing<\/pre>\n<p>Then we create an instance of the <a title=\"MindFusion UI for JavaScript: TabControl\" href=\"https:\/\/www.mindfusion.dev\/onlinehelp\/javascript.pack\/index.htm?T_MindFusion_UI_TabControl.htm\">TabControl<\/a> in code this way:<\/p>\n<pre>\/\/ Create a new TabControl.\nvar host = new ui.TabControl(document.getElementById(\"host\"));\nhost.width = new ui.Unit(70, ui.UnitType.Percent);\nhost.height = new ui.Unit(70, ui.UnitType.Percent);\nhost.theme = \"light\";<\/pre>\n<p>We use the id of the DIV element in the constructor of the <a title=\"MindFusion UI for JavaScript: TabControl\" href=\"https:\/\/www.mindfusion.dev\/onlinehelp\/javascript.pack\/index.htm?TabControl_and_TabPage.htm\">TabControl<\/a> Then we use the <a title=\"MindFusion UI for JavaScript: theme\" href=\"https:\/\/www.mindfusion.dev\/onlinehelp\/javascript.pack\/index.htm?P_MindFusion_Mapping_Control_theme_0.htm\">theme<\/a> property to refer to the theme that we want to use. The value of the <a title=\"MindFusion UI for JavaScript: theme\" href=\"https:\/\/www.mindfusion.dev\/onlinehelp\/javascript.pack\/index.htm?P_MindFusion_UI_Control_theme_0.htm\">theme<\/a> property should be the same as the name of the CSS ile that we referenced in the web page. It can point to a custom theme that you have created as long as the names of the file and the property value match.<\/p>\n<p>We create the first <a title=\"MindFusion UI for JavaScript: TabPage\" href=\"https:\/\/www.mindfusion.dev\/onlinehelp\/javascript.pack\/index.htm?T_MindFusion_UI_TabPage_Members.htm\">TabPage<\/a> as an instance of the <a title=\"MindFusion UI for JavaScript: TabPage\" href=\"https:\/\/www.mindfusion.dev\/onlinehelp\/javascript.pack\/index.htm?T_MindFusion_UI_TabPage_Members.htm\">TabPage<\/a> class:<\/p>\n<pre>\/\/ Create four templated tab pages and add them to the host's tabs collection.\nvar tab1 = new ui.TabPage(\"Owner Details\");\n\/\/ The HTML of the specified page will be set as the innerHTML of a scrollable div inside the tab content element.\ntab1.templateUrl = \"page1.html\";\nhost.tabs.add(tab1);<\/pre>\n<p>We provide the string that will render in the title of the <a title=\"MindFusion UI for JavaScript: TabPage\" href=\"https:\/\/www.mindfusion.dev\/onlinehelp\/javascript.pack\/index.htm?T_MindFusion_UI_TabPage_Members.htm\">TabPage<\/a> in the constructor. Then we set the content that the <a title=\"MindFusion UI for JavaScript: TabPage\" href=\"https:\/\/www.mindfusion.dev\/onlinehelp\/javascript.pack\/index.htm?T_MindFusion_UI_TabPage.htm\">TabPage<\/a> will have as a url to the web page that contains it e.g. the <a title=\"MindFusion UI for JavaScript: TabPage\" href=\"https:\/\/www.mindfusion.dev\/onlinehelp\/javascript.pack\/index.htm?TabControl_and_TabPage.htm\">TabPage<\/a> loads a content from a page specified with <a title=\"MindFusion UI for JavaScript: templateUrl\" href=\"https:\/\/www.mindfusion.dev\/onlinehelp\/javascript.pack\/index.htm?P_MindFusion_UI_TabPage_templateUrl_0.htm\">templateUrl<\/a> Here is the code for the first page:<\/p>\n<div style=\"padding: 10px;\"><label for=\"fname\">First Name: <\/label> <input id=\"fname\" title=\"Your first name\" name=\"First name\" required=\"\" type=\"text\" placeholder=\"John\" \/><\/div>\n<div style=\"padding: 10px;\"><label for=\"lname\">Last Name: <\/label> <input id=\"lname\" title=\"Your family name\" name=\"Last name\" required=\"\" type=\"text\" placeholder=\"Smith\" \/><\/div>\n<div style=\"padding: 10px;\"><label for=\"citizen_id\">Citizen Id:<\/label><input id=\"citizen_id\" title=\"10 digits\" max=\"9000000000\" min=\"1000000000\" name=\"Citizen number\" pattern=\"[0-9]{10}\" required=\"\" size=\"10\" type=\"number\" placeholder=\"0123456789\" \/><\/div>\n<pre><\/pre>\n<p>In terms of HTML, we have provided each input element with an id, a placeholder value and the necessary restrictions that will validate its content. We strictly use and follow the Validation API of JavaScript, which you can check here: <a title=\"JavaScript Validation API\" href=\"https:\/\/www.w3schools.com\/js\/js_validation_api.asp\">https:\/\/www.w3schools.com\/js\/js_validation_api.asp<\/a> and here <a title=\"MDN: Validation through Constraints\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/Guide\/HTML\/HTML5\/Constraint_validation\">https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/Guide\/HTML\/HTML5\/Constraint_validation<\/a>.<\/p>\n<h2>III. Data Submission and Validation<\/h2>\n<p>On the last tab of the form, we have placed a submit button:<\/p>\n<div style=\"padding: 10px;\"><button id=\"submit\">Send Data<\/button><\/div>\n<p>We wire the event handler of the click action for this button in the <a title=\"MindFusion UI for JavaScript: contentLoad\" href=\"https:\/\/www.mindfusion.dev\/onlinehelp\/javascript.pack\/index.htm?E_MindFusion_UI_TabPage_contentLoad.htm\">contentLoad<\/a> event of the fourth tab, where the button is:<\/p>\n<pre>tab4.contentLoad.addEventListener(tabLoad);\n..........................\n..........................\nfunction tabLoad(sender, args) {\n\n    let current_datetime = new Date();\n    let formatted_date = current_datetime.getFullYear() + \"-\" + (current_datetime.getMonth() + 1) + \"-\" + current_datetime.getDate();\n    sender.element.querySelector(\"#start\").value = formatted_date;\n    sender.element.querySelector(\"#submit\").addEventListener(\"click\", function () {\n    submitData(sender);\n    });\n}<\/pre>\n<p>In the event handler we get the current date and format it the way the default DateTime picker HTML control expects to get it. We get each input control through its id and the querySelector of the HTML Document object. The sender in this case is the fourth tab or tab4.<\/p>\n<p>The method that validates the content is submitData:<\/p>\n<pre>function submitData(sender) {\n    var txt = \"\";\n\n    var inputObj = tab4.element.querySelector(\"#start\");\n\n    if (!inputObj.checkValidity()) {\n        txt += inputObj.name + \": \";\n        txt += inputObj.validationMessage + \"\n\";\n        inputObj.style[\"border-color\"] = \"red\";\n        host.selectedItem = tab4;\n        dataIsCorrect = false;\n    } else\n        inputObj.style[\"border-color\"] = \"gray\";\n        ....................................<\/pre>\n<p>We use querySelector once again to get the input fields on each page one by one. For each one we see if the validity check has failed. If yes, we outline this field in red and append the validation message to a text variable.<\/p>\n<p>We walk through all tabs and all input fields in this same manner and in reverse order. Our aim is that the first tab with error gets selected, even if there are errors in fields further in the form.<\/p>\n<p>Note that if the field is OK we set its border to the default color. This way we reset the appearance of fields that were previously wrong but the user has corrected.<\/p>\n<p>Finally, we assign the text to the content of the paragraph that renders text in red:<\/p>\n<pre>...............................\ndocument.getElementById(\"error\").innerHTML = txt;  \n\n    if (txt.length === 0)\n        confirmData();<\/pre>\n<p>If no errors have been detected &#8211; that means the error text is an empty string &#8211; we submit the data. The data submission is handled by the confirmData method:<\/p>\n<pre>function confirmData() {\n\n    \/\/first tab\n    tab1.element.querySelector(\"#fname\").value = \"\";\n    tab1.element.querySelector(\"#lname\").value = \"\";\n    tab1.element.querySelector(\"#citizen_id\").value = \"\";\n    ........................................\n    ........................................\n     \/\/fourth tab\n    tab4.element.querySelector(\"#duration\").value = \"\";\n    let current_datetime = new Date();\n    let formatted_date = current_datetime.getFullYear() + \"-\" + (current_datetime.getMonth() + 1) + \"-\" + current_datetime.getDate();\n    tab4.element.querySelector(\"#start\").value = formatted_date;\n\n    ui.Dialogs.showInfoDialog(\"Confirmation\", \"Your info has been submitted!\", null, host.element, host.theme);\n\n}<\/pre>\n<p>We reset the values of all input fields and we show an instance of MindFusion <a title=\"MindFusion UI for JavaScript: InfoDialog\" href=\"https:\/\/www.mindfusion.dev\/onlinehelp\/javascript.pack\/index.htm?T_MindFusion_UI_InfoDialog_Members.htm\">InfoDialog<\/a> to inform the user that their data has been successfully collected.<\/p>\n<p><img decoding=\"async\" title=\"Multi-tabs Form: Confirmation\" src=\"https:\/\/mindfusion.dev\/samples\/javascript\/ui\/tabs_form_confirmation.png\" \/><\/p>\n<p>You can download the source code of the sample and all MindFusion themes and libraries used from this link:<\/p>\n<p align=\"center\"><a title=\"Tab Form with Validation in JavaScript: Download\" href=\"https:\/\/mindfusion.dev\/samples\/javascript\/ui\/TabForm.zip\">https:\/\/mindfusion.dev\/samples\/javascript\/ui\/TabForm.zip<\/a><\/p>\n<p>You can ask technical question about MindFusion JavaScript developer tools at the online forum at <a title=\"MindFusion Discussion Boards\" href=\"https:\/\/mindfusion.dev\/Forum\/YaBB.pl\">https:\/\/mindfusion.dev\/Forum\/YaBB.pl<\/a>.<\/p>\n<p><i>About MindFusion JavaScript UI Tools:<\/i> MindFusion UI libraries are a set of smart, easy to use and customize JavaScript UI components. Each control boasts an intuitive API, detailed documentation and various samples that demonstrate its use. The rich feature set, multiple appearance options and numerous events make the UI controls powerful tools that greatly facilitate the programmers when building interactive JavaScript applications. MindFusion UI for JavaScript is part of MindFusion JavaScript Pack. You can read details at <a title=\"MindFusion JavaScript Pack\" href=\"https:\/\/mindfusion.dev\/javascript-pack.html\">https:\/\/mindfusion.dev\/javascript-pack.html<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this blog post we will create a form that spans over several tabs. Each tab contains input fields for a specific type of information. There are placeholders and restrictions for each input field. If the provided data is not &hellip; <a href=\"https:\/\/mindfusion.dev\/blog\/multi-tabs-form-in-javascript-with-validation\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false},"version":2}},"categories":[513,74,343],"tags":[620,616,621,618,48,619],"class_list":["post-2242","post","type-post","status-publish","format-standard","hentry","category-javascript","category-sample-code","category-ui","tag-form-validation","tag-javascript-tabs","tag-js-sample-code","tag-tab-page","tag-ui","tag-validation-api"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_shortlink":"https:\/\/wp.me\/p3RlKs-Aa","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/mindfusion.dev\/blog\/wp-json\/wp\/v2\/posts\/2242","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mindfusion.dev\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mindfusion.dev\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mindfusion.dev\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mindfusion.dev\/blog\/wp-json\/wp\/v2\/comments?post=2242"}],"version-history":[{"count":5,"href":"https:\/\/mindfusion.dev\/blog\/wp-json\/wp\/v2\/posts\/2242\/revisions"}],"predecessor-version":[{"id":2652,"href":"https:\/\/mindfusion.dev\/blog\/wp-json\/wp\/v2\/posts\/2242\/revisions\/2652"}],"wp:attachment":[{"href":"https:\/\/mindfusion.dev\/blog\/wp-json\/wp\/v2\/media?parent=2242"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mindfusion.dev\/blog\/wp-json\/wp\/v2\/categories?post=2242"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mindfusion.dev\/blog\/wp-json\/wp\/v2\/tags?post=2242"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}