JavaScript for Form Validation and Dynamic UI Development

Elements of Element Content and Hierarchy Recap

  • Content Retrieval and Modification: In JavaScript, there are two primary methods used to set or get the content residing within elements. This refers to the data inside the tags, such as text or child elements, rather than the element itself.
    • The textContent Property: This is used to extract or update the text within an element. It is often used for simple text strings as it does not parse the content as HTML code.
    • The innerHTML Property: This property allows for the retrieval or definition of the HTML content inside an element. It can be used to set new content, which can include adding other nested children elements.
  • CSS Interaction via JavaScript: There are two main methodologies for manipulating the visual style of a webpage using JavaScript:
    • The Style Object: By accessing an element’s style object, developers can target individual CSS properties (such as color, border, or display) and assign them specific values directly.
    • Class Name Overriding: JavaScript can be used to change or override the existing class name of an element (‘className’). This allows the element to adopt a new set of predefined CSS rules from an external stylesheet.
  • DOM Hierarchy Terminology: Nodes within the Document Object Model (DOM) that exist on the same hierarchical level are referred to as sibling nodes. This relationship is a critical component of the parent-child structure that defines the DOM.

Foundational Principles of Data Validation

  • Goal of Data Validation: The objective is to verify that data meets specific requirements before it is sent to a server for database storage. The process results in either the acceptance of valid data or the rejection of invalid data, accompanied by a message explaining the error to the user.
  • The Three-Phase Validation Cycle:
    • Phase 1 and 2 (Database Design): The process begins with designing the database to determine exactly what information needs to be collected.
    • Phase 3 (Format Specification): Before constructing forms, the necessary format for each piece of data (data type, length, etc.) must be defined.
    • Form Construction: Once requirements are clear, HTML forms are created using input elements that reflect the database’s expectations.
  • Event Capturing in Validation:
    • Submit Event: Captures the moment a user attempts to send the form data, allowing for a final validation check.
    • onChange Event: This event triggers every time a change occurs within an input field, such as when a user types a new character. It allows for real-time validation and interaction.
  • Common Validation Scenarios:
    • Check for empty fields (missing information).
    • Validate email address formats.
    • Verify if a given age is biologically or legally possible.
    • Ensure postal codes follow specific regional formats.
    • Test for password strength.

Native HTML Built-in Validation and Type Constraints

  • Built-in vs. Custom Validation: HTML5 provides native attributes to handle validation without requiring JavaScript, though it has limitations including inconsistent browser reactions and difficulty in customizing default error messages.
  • Input Types for Validation: Specific ‘type’ attributes automatically trigger basic validation for specialized data types:
    • emailemail: Validates basic email structure.
    • urlurl: Validates web addresses.
    • numbernumber: Only allows numeric input.
    • datedate: Provides a date picker interface and format.
    • teltel: Used for telephone numbers.
    • colorcolor: Provides a native color picker UI.
  • The Pattern Attribute and Regular Expressions: For more complex data patterns, the patternpattern attribute is utilized. It uses regular expression matching.
    • Syntax Variance: Unlike database-level regular expressions, HTML pattern attributes assume an anchor at the start and end of the string. Therefore, the caret (\wedge) and dollar sign () symbols are not required.\n * **Example Pattern**: To enforce an email that starts with 2alphabeticcharactersfollowedbyalphabetic characters followed by4digitsandendswithdigits and ends with@vicado.ac.nz,thepatternvalueis:, the pattern value is:’[A-Z]{2}[0-9]{4}@vicado.ac.nz’.\n* **Additional Formatting Attributes**:\n * **Required Attribute**: Prevents form submission if the associated input field is empty.\n * **Min and Max Attributes**: Used with number types to set inclusive numeric thresholds. For example, setting min=18preventsvaluesbelowprevents values below18.\n * **Placeholder Attribute**: Provides a temporary value visible in the input field until the user begins typing. Previously requiring CSS and JavaScript, this is now a native HTML5 feature via the placeholder attribute.\n * **Title Attribute**: In many browsers, the text provided in the title attribute is displayed to the user alongside the default browser error message when a pattern match fails.\n\n# JavaScript-Based Validation Strategies\n\n* **Field-Level Validation**: This involves checking individual input elements to see if they meet specific rules, such as checking if a required text field is empty or if a username meets a length requirement of at least 6 characters. This can often overlap with HTML-based validation.\n* **Cross-Field Validation**: This is where JavaScript is uniquely effective. It involves checking the logical consistency between multiple independent input fields.\n * **Example Logic Case**: A user might enter a birth date that implies they are 14yearsold,butalsoinputthattheyhaveheldadriverslicenseforyears old, but also input that they have held a driver's license for3 years. While both individual inputs are valid formats, they are logically inconsistent. JavaScript can capture and reject such dependencies.\n\n# Technical Implementation of JavaScript Validation\n\n* **Data Acquisition**: To validate user input, the script must first target the element and then extract its contents.\n * **Recommended Method**: Use document.getElementById(‘id’).value to retrieve the data currently typed into the field.\n * **Alternative (Old) Method**: Accessing elements through the form name via document.formName.inputName.value. This is less recommended than the ID-based approach.\n* **JavaScript Validation Function Structure**:\n * Functions typically utilize an ‘if’ statement to check if the extracted value is empty (e.g., ’’) or fails a regex test.\n * A global boolean variable, such as formIsValid,isoftensetto, is often set totruebydefaultandbecomesby default and becomesfalse if any specific validation check fails.\n* **Custom Error Messaging via the DOM**:\n * Errors in JavaScript allow for highly customized reporting compared to HTML pop-ups. A display function (e.g., displayError) can be created taking two parameters: the specific element and the message string.\n * **Creating the Error Element**: Use document.createElement(‘span’) to generate a new element to hold the message.\n * **Setting Content and Style**: Content is added via textContent.Visualcues(likesettingthefontcolortored)areappliedusingthestyleobject:. Visual cues (like setting the font color to red) are applied using the style object:element.style.color = ‘red’.\n * **DOM Insertion**: To place the error on the page, the algorithm involves getting the handle of the target element’s parent node (element.parentNode)andusingthe) and using theinsertBefore method.\n * **Syntax for Placement**: parentNode.insertBefore(messageElement, element.nextSibling) ensures the error appears as a sibling immediately following the input field.\n* **Preventing Duplicate Error Messages**: When a validation function runs repeatedly (e.g., on multiple submit clicks), it may spam duplicate error messages. This can be mitigated by an ‘if’ condition that checks if the next sibling is already a span or has current error text, stopping the function if an error is already present.\n\n# Form Submission Logic and Multi-Level Checks\n\n* **The onSubmit Attribute**: Form elements can include an onSubmitattribute,whichtriggersaJavaScriptvalidationfunction.Itmustbewrittenasattribute, which triggers a JavaScript validation function. It must be written asreturn\ formIsValid().\n * If the function returns true, the form proceeds to submit to the server.\n * If the function returns false, the submission is halted.\n* **Modular Validation**: A clean design involves separate functions for each input field (e.g., checkUsername(),,checkEmail()).Thesefunctionsupdateglobalstatusvariablesthatthemain). These functions update global status variables that the mainonSubmitfunctionchecksbeforedecidingtoreturnfunction checks before deciding to returntrueororfalse.\n\n# Design Strategies for Error Prevention\n\n* **Prevention vs. Reaction**: Effective UI design aims to prevent invalid data from being entered rather than simply reacting to errors after they occur.\n* **Visual Guidance and Length Restriction**: Using CSS to size input fields appropriately gives users a visual hint of expected length. The maxLengthattributecanphysicallystopauserfromtypingmorethanasetnumberofcharacters(e.g.,attribute can physically stop a user from typing more than a set number of characters (e.g.,5 characters).\n* **Selective Inputs**: Eliminating invalid choices entirely by using radio buttons, checkboxes, or dropdown lists instead of free-text fields.\n* **Reflecting Data Structure**: Breaking patterns into multiple fields. For a credit card number, instead of one large field for 16digits,fourseparatefieldsofdigits, four separate fields of4 digits each help the user align with the expected data structure.\n* **Dynamic Dependency Management**: Showing, hiding, or disabling fields based on previous selections to ensure only relevant and logical data is requested.\n\n# Dynamic HTML and Interdependent Interactivity\n\n* **Enable/Disable Method**: Inputs can be grayed out using the disabledattribute.ThroughJavaScript,theattribute. Through JavaScript, thedisabledpropertyistoggledbetweenproperty is toggled betweentrueandandfalse based on events like clicking a specific radio button.\n* **Show/Hide Method**: This technique uses CSS to make elements vanish until needed.\n * **Implementation**: An element can be hidden by default using the CSS property display: none.\n * **JavaScript Trigger**: When a specific condition is met (e.g., the ‘Credit Card’ radio button is ‘checked’), JavaScript updates the style object to display: block, making the interlinked fields appear.\n * **Grouping**: For radio buttons, assigning the same name attribute ensures they function as a group where only one option can be selected at a time.\n\n# Questions & Discussion\n\n* **How do we connect HTML and JavaScript?**: The scriptelementisusedatthebottomofthebody.Onemustspecifytherelativepathtothefileusingtheelement is used at the bottom of the body. One must specify the relative path to the file using thesrc$$ attribute.
  • What is the difference between HTML Regular Expressions and standard ones?: In the pattern attribute, HTML assumes the pattern starts at the beginning and ends at the end of the input, making anchors like the caret and dollar sign unnecessary.
  • What if I set a hidden field to be required?: This is considered a poor form design. If a field is hidden because it is dependent on another selection that hasn’t been made, setting it to required would prevent the form from submitting without giving the user a way to correct the error.