Tips for Implementing Input Validation in Your Code

I have been attempting to design a multi-form and have been struggling to add input validation. Specifically, I want to prevent the form from progressing to the next step if certain fields (such as name) are left empty. However, despite multiple attempts, I have not been able to achieve the desired results or display error messages. This has led me to seek guidance on how to implement validation for name, email, and password in my multi-form setup. For instance, upon clicking the next button, I require input validation for email using the regex pattern ^[\w\d._-]+@[\w\d.-]+\.[\w\d]{2,6}$ and for password using ((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,15}). If the input does not meet these requirements, the system should display messages indicating that either the email format or the password format is incorrect. Below is the script I am currently working with:

$(document).ready(function(){
          $(".form-wrapper .button").click(function(){
            var button = $(this);
            var currentSection = button.parents(".section");
            var currentSectionIndex = currentSection.index();
            var headerSection = $('.steps li').eq(currentSectionIndex);
            currentSection.removeClass("is-active").next().addClass("is-active");
            headerSection.removeClass("is-active").next().addClass("is-active");

            $(".form-wrapper").submit(function(e) {
              e.preventDefault();
            });

            if(currentSectionIndex === 2){
              $(document).find(".form-wrapper .section").first().addClass("is-active");
              $(document).find(".steps li").first().addClass("is-active");
            }
          });
        });
html, body{
          width: 100%;
          height: 100%;
          margin: 0;
          padding: 0;
          font-family: 'Open Sans', sans-serif;
          background-color: #3498db; 
          <!-- remaining stylesheet code unchanged -->
          
        </body>
        </html>

Answer №1

To achieve this, you can utilize the required attribute. For more information on different validation types, please refer to the documentation.

I have set up two separate forms to validate input upon each button click.

$(document).ready(function(){

      $(".form-wrapper .button").click(function(){
       
           var inpObj = document.getElementById("form1");
          if (inpObj.checkValidity()) {
  
        var button = $(this);
        var currentSection = button.parents(".section");
        var currentSectionIndex = currentSection.index();
        var headerSection = $('.steps li').eq(currentSectionIndex);
        currentSection.removeClass("is-active").next().addClass("is-active");
        headerSection.removeClass("is-active").next().addClass("is-active");

        $(".form-wrapper").submit(function(e) {
         e.preventDefault();
        });
        if(currentSectionIndex === 0){
          $(document).find("#section2").addClass("is-active");      
        }
        if(currentSectionIndex === 2){
          $(document).find("#form2 .section").addClass("is-active");
          $(document).find(".steps li").first().addClass("is-active");
        }
        }
      });
      
    });
html, body{
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
      font-family: 'Open Sans', sans-serif;
      background-color: #3498db;
    }

    // Remaining CSS code goes here...

    </style>  
    </head>

    <body>
        <div class="container">
        <div class="wrapper">
          <ul class="steps">
            <li class="is-active">Step 1</li>
            <li>Step 2</li>
          </ul>
          <form class="form-wrapper"  id="form1">
            <fieldset class="section is-active">
              <h3>Your Details</h3>
              <input type="text" name="name" id="name" placeholder="Name" required>
              <input type="text" name="email" id="email" placeholder="Email" required>
              
               <button class="button">Next</button>
            </fieldset>
          </form>
              <form class="form-wrapper" id="form2">
            <fieldset class="section" id="section2">
              <h3>Choose a Password</h3>
              <input type="password" name="password" id="password" placeholder="Password">
              <input type="password" name="password2" id="password2" placeholder="Re-enter Password">
              <input class="submit button" type="submit" value="Sign Up">
            </fieldset>
            <fieldset class="section" id="section3">
              <h3>Account Created!</h3>
              <p>Your account has now been created.</p>
              <div class="button">Reset Form</div>
            </fieldset>
          </form>
        </div>
      </div>
    </body>
    </html>

Answer №2

Implement the required attribute within the input tag to ensure the field is mandatory

<form class="form-wrapper">
            <fieldset class="section is-active">
              <h3>Enter Your Information</h3>
              <input type="text" name="fullname" id="fullname" placeholder="Full Name" required>
              <input type="email" name="emailaddress" id="emailaddress" placeholder="Email Address" required>
              <input class="button" type="button" value="Next">
            </fieldset>
            <fieldset class="section">
              <h3>Create a Password</h3>
              <input type="password" name="userpassword" id="userpassword" placeholder="Password" required>
              <input type="password" name="confirmpassword" id="confirmpassword" placeholder="Confirm Password" required>
              <input class="submit button" type="submit" value="Sign Up">
            </fieldset>
            <fieldset class="section">
              <h3>Account Successfully Created!</h3>
              <p>Congratulations, your account has been successfully created.</p>
              <div class="button">Reset Form</div>
            </fieldset>
          </form>

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

Issue with ThreeJs raycaster not returning correct event.clientY value when header bar is visible

Here's the issue: I'm trying to place a sphere on a 3D model when I click on it using ThreeJs raycaster. It works fine when the canvas covers the entire page, but if I add a header bar to the page, the positioning is off. Here are some visual ex ...

Is there a way to retrieve the chosen selection from a select dropdown element using JavaScript?

As someone who is still learning JavaScript, I've come across a particular issue. Within a webpage, there is a select dropdown as shown below: <select id="selTipoRap" class="form-control" th:field="*{tipoRappresentante}&qu ...

Can you explain the {| ... |} syntax in JavaScript to me?

While reviewing a javascript codebase, I stumbled upon a section of code that appears as follows: export type RouteReducerProps = {| error?: Error, isResolving: boolean, isResolved: boolean, hasFailed: boolean, |}; Upon closer inspection, it seem ...

The OnClick event is unresponsive when accessing the website on a mobile browser

I have a HTML page where I've included an onclick event in a div tag. Within this event, I'm using location.href = url to open a specific URL. Surprisingly, this works perfectly fine in a web browser but strangely doesn't work in a mobile br ...

Converting HTML to PDF: Transform your web content into

I have a couple of tasks that need to be completed: Firstly, I need to create a functionality where clicking a button will convert an HTML5 page into a .PDF file. Secondly, I am looking to generate another page with a table (Grid) containing data. The gr ...

Implementing a feature to automatically set the datepicker value to the selected date upon page initialization

I am working with a datepicker element, identified by id="from_dt", and a button with id="fromToDate". When a date is selected from the datepicker and the button is clicked, the page will load. At that point, I want to transfer the selected date to a textb ...

JS seems to kick in only after a couple of page refreshes

I'm facing an issue with my 3 columns that should have equal heights. I've implemented some JavaScript to achieve this, which you can see in action through the DEMO link below. <script> $(document).foundation(); </script> <scri ...

Experiencing Issues with the Email Button Functionality on My Website

I am looking to create an "Email" button that will send the user-entered text to my email address. Here is the code snippet: <form method="post" action="malto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cb ...

What is preventing d3.json from including cookies in the request?

I'm delving into the world of ajax requests with d3.js (v5) and I'm facing a little hiccup. Here's my code snippet: d3.json(uri).then(data =>console.log(data)); When I tried this in an app utilizing cookie authentication, I consistently ...

What is the best way to determine the value of margin-left in inline CSS using jQuery?

Here is the code snippet I am working with: <div class="ongoing" style="width: +728px; margin-left: +12480px"> I need to extract the value of the margin-left property for scrolling purposes. The technique I used to retrieve the width value does no ...

The CSS styles for a:link, a:active, and a:visited do not seem to work with

My page contains the following CSS rule: a:link,a:active,a:visited{text-decoration:none;} I have encountered an issue where this rule is not working as expected. To apply the rule within a div with the id="test", I had to modify the rule like this: #tes ...

unable to retrieve / interpret data from herdsmen using fetch

When sending a request to a node server, the server responds with headers and a blank body. Despite being able to view the headers in the network activity panel within dev-tools, I faced difficulties reading them using the following code: let uploaded ...

Transitioning my website to incorporate Angular JS

Recently, I have been exploring AngularJS and I am quite impressed with its features. I am currently developing a website using traditional methods (php, html, css, mysql, some jQuery) and I am considering transitioning to Angular. The reason for this chan ...

The filter() and some() functions are not producing the anticipated output

Currently, I am in the process of developing a filtering mechanism to sift through a dataset obtained from an API. The array that requires filtering contains objects with various parameters, but my aim is to filter based only on specific parameters. For ...

Issue with nested tabs functionality within a pill tab panel in Bootstrap not functioning as expected

I'm facing a challenge with integrating tabs into a vertical pill tab panel in Bootstrap 4. Below is a brief code snippet: <html> <head> <link href="bootstrap.min.css" rel="stylesheet"> </head> <body> <script ...

"Subtle Website Background Fade Effect When Menu is Hovered Over

Click on the following link to observe a transition effect that occurs on the body of the website when interacting with the main menu system: Here is the website Do you know what this effect is called and how it can be integrated into a website? ...

Show the current time using Moment.js

I am currently working on developing a clock component that displays the current time in real-time. Issue: The initial time is correctly displayed when the page loads (HH:mm A), but the clock does not update dynamically. clock.component.ts : import { ...

Using json_encode in PHP results in nullification of HTML strings

I am working with an array that includes a string containing HTML tags as one of its elements. As I loop through the array and output the field, I can see the string. $positions = $jobs_dbc->getData($sql); foreach($positions as $position) { ...

How to update a boolean value in a JSON object using AngularJS?

Trying to modify a boolean value when a user clicks on a JSON-populated table row. Here's an example of the setup... $scope.prices = { "Prices": [ { "Code": "edl", "Selected": false }, { "Code": "ead", "Sel ...

Ways to modify the background hue of a Bootstrap popover

I am trying to create 3 popovers with different background colors using Bootstrap and CSS. Ideally, I would like the background color to change based on the specific letter placed inside the span's class attribute. <div class="container"& ...