Tips for implementing validation in a multi-step form as outlined in w3schools tutorial

I came across a multistep form creation tutorial on w3schools. However, the tutorial only covers generic validation (checking if a field is empty), which is not sufficient for my needs. How can I implement HTML validation (e.g., min, max, length) for text and email fields? Is there a way to customize the validation process without having to write validation for each individual field, considering the form contains many fields?

index.html


        <!doctype html>
        <html lang="en">
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
                   
                <title>Personal</title>
                <link href="./css/bootstrap.min.css" rel="stylesheet" type="text/css" />
                <link href="./css/all.css" rel="stylesheet" type="text/css" />
                <link href="./css/personal.css" rel="stylesheet" type="text/css" />
                <style> 
                </style>
            </head>
        
            <body>
                <main>
                    <div class="container py-5">
                        <form id="students-registration" class="jumbotron">
        
                            <div class="tab">
                                <h2 class="lead text-center">Demographic Information</h2>
                                <div class="form-row">
                                    <div class="form-group col">
                                        <input type="text" class="form-control form-control-sm" placeholder="Surname">
                                    </div>
                                    <div class="form-group col">
                                        <input type="text" class="form-control form-control-sm" placeholder="First name">
                                    </div>
                                    <div class="form-group col">
                                        <input type="text" class="form-control form-control-sm" placeholder="Middle name">
                                    </div>
                                </div>
                            </div>
        
                            <div class="tab">
                                <h2 class="lead text-center">Medicals</h2>
                                <div class="form-row col-md-4 pl-0 pb-1">
                                    <label for="">How would you rate your health</label>
                                    <select class="form-control form-control-sm" name="" id="">
                                        <option value="Good">Good</option>
                                        <option value="Fair">Fair</option>
                                        <option value="Poor">Poor</option>
                                    </select>
                                </div>
                            </div>
        
                            <div style="overflow:auto;">
                                <div style="float:right;" class="p-2">
                                    <button type="button" class="btn btn-sm btn-info" id="prevBtn">Previous</button>
                                    <button type="button" class="btn btn-sm btn-success" id="nextBtn">Next</button>
                                </div>
                            </div>
                            
                            <!-- Circles indicating the steps of the form: -->
                            <div style="text-align:center; margin-top:40px;">
                                <span class="step"></span>
                                <span class="step"></span>
                                <span class="step"></span>
                                <span class="step"></span>
                            </div>
                        </form>
                    </div>
                </main>
        
                <footer> 
        
                </footer>
                
                <script src="./js/jquery-3.3.1.min.js"></script>
                <script src="./js/popper.min.js"></script>
                <script src="./js/bootstrap.min.js"></script>
                <script src="./js/scripts.js"></script>
        
            </body>
        </html>
    

scripts.js


        // JavaScript code for form validation and navigation
    
        // Function to display the current tab
        // Function to navigate to the next or previous tab
        
    

Is there a way to prevent the form from progressing to the next step unless the current step is valid?

Answer №1

  • JavaScript validation may not be necessary, as the browser can validate forms in the user's language by utilizing appropriate attributes such as type, pattern, min, max, required, maxlength, and minlength.
  • To trigger validation, consider using the submit event instead of a button click event, and utilize event.preventDefault() to prevent the default behavior. This allows the browser to validate the form using constraint validation.

If you prefer a different visual style for validation, explore the validation API and features like the input.validity object.

Answer №2

To include an attribute in the input field on your HTML page, you'll need to make some adjustments to the code. Enclose all the logic within form tags and trigger form submission using a button. Remember to add e.preventDefault() as mentioned in another answer.

For further details, refer to this link: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes

When you want to require the input to be filled, add the "required" attribute like this:

<input type="text" required >

For specifying a minimum length, use the "minlength" attribute:

<input type="text" required minlength="5">

If you need to validate an email input, use the "email" type:

<input type="email" >

This will check if the input resembles an email address.

If you encounter any issues, you may have to implement custom validation.

For additional guidance, watch this video: https://www.youtube.com/watch?v=In0nB0ABaUk

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with the ::after element in my React component for my latest React 3D portfolio project

For my portfolio project, I am following a tutorial by LamaDev (https://www.youtube.com/watch?v=qALsVa-V9qo&t=2334s&ab_channel=LamaDev). At around timestamp 36:40, he creates a ::after selector which is not working for me, even though the rest of t ...

What is the process for uploading a JSON file from your local drive?

I am attempting to use jQuery to load a local JSON file. The code seems to be functioning properly, but for some reason, the data is not being made available in an array. $.getJSON("/ajax/data/myjasonfile.json", function(json) { console.log(js ...

Discover the element's selector for the event that was triggered using jQuery

In the process of creating a lightweight real-time application, we are utilizing jQuery's event system to facilitate communication between modules. Any changes made in the DOM that affect elements outside the module are achieved through triggering eve ...

What is the best way to deactivate a button using AngularJS?

$scope.date = moment(currentDate); $scope.date1 = moment(currentDate).add(-1, 'days'); function checkDate(){ if ($scope.date > $scope.date1) { return true; } else{ return false; } }; checkDate(); ...

Unable to fetch the data from HTML input field using autocomplete feature of jQuery UI

I am facing an issue with my html autocomplete textbox. Whenever I try to enter an address like "New York" and click on the submit button, it does not retrieve the input value and returns no value. Test.aspx <!--Address--> <div class="form-g ...

In PHP, the symbol "!=" is used to compare if a string is not equal to a

Seeking feedback on why setting a string variable prevents me from calling it within a function. For instance: $name = "name"; $quote_name = "'".$name."'"; //echo of $name = name //echo of $quote_name = 'name' In PHP, I encounter iss ...

Unable to disable background color for droppable element

For my project, I am working with two div boxes. My goal is to make it so that when I drag and drop box002 into another div box001, the background color of box001 should change to none. I have attempted to achieve this functionality using jQuery without s ...

Utilizing ScrollView Component in React Native

I have developed a simple app that displays a collection of images with titles, resembling a film gallery where all available films can be viewed. However, I encountered an issue when trying to implement the ScrollView element as it does not allow for scro ...

Create a consistent number based on quantity

Looking to generate a sequence of numbers equal to the count in PHP or JavaScript for my application. For example, if my total count is 7: <?php $total = 7; I would like to generate seven 1's like this: $split_one = [1,1,1,1,1,1,1]; If my count ...

Steps for adding information to a sub tag within an XML document

Imagine having this example tag <root> <foo> </foo> </root> with the following html form <form action="foo.php method="post"> <input type="text" name="something"> <input type=" ...

jQuery Does Not Iterate Through Arrays

I am encountering an issue where I am trying to populate an array with images and then pass them to a variable called $image. However, when I attempt to iterate over this array, the same item is being alerted three times. Here is the problematic code snip ...

What is the best way to target specific text within the DOM without including text within attributes?

We are currently displaying search results from various posts on our website, and we would like to highlight the search terms in the displayed content. Currently, we are implementing this functionality on the backend using PHP. We iterate through the post ...

Is it possible to create a popup without using JavaScript?

Is it feasible to create a popup window without utilizing JavaScript by using the href tag or a similar method? For example, could something like <a href="popup:http://stackoverflow.com">Stackoverflow Popup</a> be used where the popup: functio ...

Scrolling vertically using window.open functionality

I am trying to open a pop-up window using window.open. I would like the scrollbars to appear only if necessary. Unfortunately, in Safari, the scrollbars do not show up unless I include scrollbars=1 in the code. However, this also causes horizontal scrollb ...

Array logging mistakenly outputs a number

I needed to access the data from JSON outside of the xml function so that I could use it in multiple functions. When I initially logged the data, it displayed arrays with objects in it. However, when I checked the length instead, it returned zero. After re ...

What is the best way to choose two <li> elements with multiple classes in my WordPress navigation menu?

I am looking for a JavaScript function that will add the class "current_highlight" when an element with the class "activo2" also has the class "active". Here is my HTML code: <div class="navbar-header"> <button type="button " class="navbar-to ...

The JavaScript slideshow fails to display an image during one rotation

The slideshow displays a sequence of images from pic1.jpg to pic8.jpg, followed by a 4-second pause with no image, and then repeats starting again at pic1.jpg. I am looking to have it loop back to pic1.jpg immediately after displaying pic8.jpg. Below is t ...

Is it possible to use jQuery validate for remote parsing with two fields in a single call

Currently, I am facing an issue while trying to parse two values using jQuery's validate plugin to compare with an SQL database. The DateReceived value is successfully parsed, but the CentreID value always appears as null. Below is the code snippet I ...

Three.js- I am having trouble with my shadow rendering, as lots of black lines are appearing everywhere instead of the shadows showing

Having recently delved into Three.js, I managed to add shadows to my model with the help of some knowledgeable individuals. However, upon the light hitting the model, numerous lines appear, causing me to question whether it's due to my poor modeling s ...

Is it possible to perform a local multipleSearch programmatically using free-jqgrid?

Despite spending countless hours and even days searching, I have yet to find a satisfactory solution to my dilemma: All I desire is to utilize the local search/filter capabilities of jqgrid (currently using free-jqgrid 4.9.0) programmatically. I am hopin ...