Submit form only if the field value is valid

I created a form with an input field that captures the user's mobile number and validates it to ensure it begins with '0'. The validation process is functioning correctly, but I am encountering a problem when submitting the form. Even if the input field contains an invalid value, the form is still submitted. I would like the form to only be submitted if the field has a valid mobile number input.

Below is the code snippet:

$('#mobili').focusout(function() {
  $('#mobili').filter(function() {
    var mobi = $('#mobili').val();
    var mobiback = $('#mobili');
    var mobilReg = /^([0][0-9]{10})$/;
    if (!mobilReg.test(mobi)) {
      $("#error-nwl").css('color', '#ff6666');
      $("#error-nwl").text("Enter a valid mobile number (must begin with 0)");
    } else {
      $("#error-nwl").css('color', '#66cc66');
      $("#error-nwl").text("ok");
    }
  })
});

$(".newslside").submit(function(e) {
  var url = "page2.html";
  alert("Submitted");
  $.ajax({
    type: "POST",
    url: url,
    data: $(".newslside").serialize(),
    success: function(data) {
      $(".errori").html(data),
        alert("Submitted");
    }
  });
  e.preventDefault();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="error-nwl"></div>
<form action="" method="post" name="myForm" class="newslside">
  <input type="text" placeholder="Mobile" name="mobile" id="mobili" maxlength="11" required />
  <br/>
  <button class="submitnews" type="submit">Send</button>
</form>

Thank you

Answer №1

Hopefully, this solution will be effective,

$('#contactPhone').focusout(function() {
   $('#contactPhone').filter(function() {
   var phone = $('#contactPhone').val();
   var phoneInput = $('#contactPhone');
   var phoneRegex = /^([0][0-9]{10})$/;
   if (!phoneRegex.test(phone)) {
      $("#error-message").css('color', '#ff6666');
      $("#error-message").text("Please enter a valid phone number (starting with 0)");
   } else {
      $("#error-message").css('color', '#66cc66');
      $("#error-message").text("Valid phone number");
   }
 })
});

$("#contactForm").submit(function(e) {

     var phone = $('#contactPhone').val();
     var phoneInput = $('#contactPhone');
     var phoneRegex = /^([0][0-9]{10})$/;
     if (!phoneRegex.test(phone)) {
         $("#error-message").css('color', '#ff6666');
         $("#error-message").text("Please enter a valid phone number (starting with 0)");
         return false;
     }else{
         var url = "confirmation.html";
         alert("Form submitted successfully");
         $.ajax({
            type: "POST",
            url: url,
            data: $("#contactForm").serialize(),
            success: function(data) {
               $(".form-response").html(data),
               alert("Form submitted successfully");
            }
         });
    }
       e.preventDefault();
 });

Answer №2

Give this a try:

$(document).ready(function(){
$(".newslside").submit(function(e) { var url = "page2.html";
  alert("Submitted");
$.ajax({ type: "POST", url: url, data: $(".newslside").serialize(),
 success: function(data) { $(".errori").html(data),
   alert("Submitted");
  } }); e.preventDefault();

 }); 
  
     $('#mobili').filter(function() {
        var mobi = $('#mobili').val();
        var mobiback = $('#mobili');
        var mobilReg = /^([0][0-9]{10})$/;
        if (!mobilReg.test(mobi)) {
            $("#error-nwl").css('color', '#ff6666');
            $("#error-nwl").text("Enter valid mobile number (begin with 0)");
        } else {
            $("#error-nwl").css('color', '#66cc66');
            $("#error-nwl").text("ok");
        }
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="error-nwl"></div>
    <form action="" method="post" name="myForm" class="newslside">
    <input pattern="[0-9]{10}" type="text" placeholder="Mobile" name="mobile" id="mobili" maxlength="11" required /><br/>
    <input type="submit" class="submitnews" value="Send"/>
    </form>

Answer №3

I've implemented the onsubmit attribute in HTML and it seems to be working well. Hopefully, this solution fits your needs.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

    <script type="text/javascript">
    function validate() {
        var mobi = $('#mobili').val();
        var mobilReg = /^([0][0-9]{10})$/;
        if (!mobilReg.test(mobi)) {
            $("#error-nwl").css('color', '#ff6666');
            $("#error-nwl").text("Enter valid mobile number (begin with 0)");
            return false;
        } else {
            $("#error-nwl").css('color', '#66cc66');
            $("#error-nwl").text("ok");
            var url = "page2.html";
            alert("Submitted");
            $.ajax({
                type: "POST",
                url: url,
                data: $(".newslside").serialize(),
                success: function(data) {
                    $(".errori").html(data),
                    alert("Submitted");
                }
            });
            e.preventDefault();
        }
    }
    </script>
</head>
<body>
    <div id="error-nwl"></div>
    <form action="" method="post" name="myForm" class="newslside"  onsubmit="return(validate());">
        <input type="text" placeholder="Mobile" name="mobile" id="mobili" maxlength="11" required />
        <br/>
        <button class="submitnews" type="submit">send</button>
    </form>
</body>
</html>

Answer №4

            <html>
        <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        </head>
        <body>
            <div id="error-nwl"></div>
            <form action="" method="post" name="myForm" class="newslside">
            <input type="text" placeholder="Mobile" name="mobile" id="mobili" maxlength="11" required /><br/>
            <button class="submitnews" type="submit">send</button>
            </form>
        <script>
        var valid = false;
        function checkValidity()
        {
        $('#mobili').focusout(function() {
            $('#mobili').filter(function() {
                var mobi = $('#mobili').val();
                var mobiback = $('#mobili');
                var mobilReg = /^([0][0-9]{10})$/;
                if (!mobilReg.test(mobi)) {
                    $("#error-nwl").css('color', '#ff6666');
                    $("#error-nwl").text("Enter valid mobile number (begin with 0)");
                    valid = false;
                } else {
                    $("#error-nwl").css('color', '#66cc66');
                    $("#error-nwl").text("ok");
                    valid = true;
                }
            })
        });

        }
        checkValidity();
        </script>
        <script>
        $(".newslside").submit(function(e) { 
        checkValidity();
        if(!valid )
        {
            return false;
        }
        var url = "page2.html";
          alert("Submitted");
        $.ajax({ type: "POST", url: url, data: $(".newslside").serialize(),
         success: function(data) { $(".errori").html(data),
           alert("Submitted");
          } }); e.preventDefault();

         }); 
        </script>

        </body>
        </html>

Answer №5

Include validation for the field within the onsubmit function of jQuery. Additionally, make sure to include a return false statement in your form tag.

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

Does width change based on position?

When I set position:absolute for an element, its width remains constant regardless of the text inside. However, if I set position:relative for the same element, the width will adjust based on the text content. I have created a fiddle with two menus, each ...

Ways to incorporate a while loop into a randomizing function

I've been diving into JavaScript and managed to create a website that displays random gifs when clicked from an array. Now, my goal is to implement a while loop to prevent duplicate images from being shown consecutively. However, I seem to be facing ...

Properly saving intricate form information in a React application

In my React project, I have a complex form consisting of multiple sub-components. Some parts of the form use nested objects as data, making it a bit challenging to manage. The main component, referred to as EditForm, holds the entire object tree of data. ...

Using environmental variables in Nuxt 2 or Nuxt 3 - a step-by-step guide

I have an .env file located in the root of my project. In my nuxt config, I am using variables to configure ReCaptcha as shown below: import dotenv from 'dotenv' dotenv.config() export default { modules: [ ['@nuxtjs/recaptcha&ap ...

The button effortlessly transforms into a sleek email submission form

I have a button that is already styled with basic CSS properties for active and hover states. I would like to add functionality so that when the "Join the Loop" button is clicked, it transforms into a simple email form similar to the one found at Apologie ...

Ensure that the div element spans the entire width of the screen

Having issues working with the div tag and encountering this problem: The left side doesn't extend as far as the right side, despite testing in multiple browsers. Here is the HTML code being used: <!DOCTYPE html> <html lang="en"> <h ...

Were you intending to import the file firebase/app/dist/index.cjs.js?

Encountering the following error message: Error: Directory import 'C:\Users\My Name\Documents\Code\WebProjects\nextfire-app\node_modules\firebase\app' is not supported when resolving ES modules import ...

AngularJS Class Confirmation Button

I'm currently working on implementing a "confirm" button for users of my website to see after clicking a specific button, using an angularJS class. Below is the code snippet I have written: class TodosListCtrl { constructor($scope, $window){ $s ...

Resolve the issue of autofill data overlapping with field labels

My form incorporates the Canada Post AddressComplete tool, which functions similarly to Google Maps Autocomplete. As you type your address, suggestions appear in a drop-down menu. However, after selecting an address, the text in the Postal Code and City f ...

Ways to extract pertinent information from a PHP API

I've been attempting to add parameters to my query, but I keep getting inconsistent results. Despite trying different methods, I haven't been successful. Take a look at the code below. First, here is my code that functions properly without using ...

The navigation bar is positioned at the forefront, blocking any elements from being displayed beneath it

I just started using Bootstrap and I'm facing an issue with my navbar. No matter what I do, anything I place goes behind it. Even with margins and the native padding from Bootstrap, I can't get the distance right because the div that I want to mo ...

Top Bootstrap dropdown menu overlaid with Leaflet zoom buttons

I'm encountering an issue depicted in the screenshot below. Is this related to bootstrap or leaflet? How can I adjust the position/style of the dropdown menu so that it appears above all other elements? https://i.sstatic.net/cQhN5.png ...

What are some strategies for blocking URL access to a controller's method in Rails 3?

My goal is to enhance my Rails 3 application by integrating Javascript/jQuery code that retrieves data from the server and updates the page based on the fetched information. I am considering implementing jQuery's $.get() method for this purpose: $.g ...

Using the jQuery function in conjunction with Infinite Ajax Scroll provides a seamless scrolling

Utilizing jQuery for filtering options can enhance the user experience. For instance, selecting the "dead" option displays only rows with the status "dead". However, when implementing infinite Ajax scroll to load new data from the database, the filter sett ...

Tips for effectively utilizing the useDraggable and useSortable hooks within the dnd-kit library

I'm currently working on developing a basic calculator using React and dnd-kit. The idea is to have draggable elements in the calculator that can be sorted within a droppable area with smooth animation effects. However, I've encountered an issue ...

Limit the bootstrap datepicker to display only certain dates and today's date

I've integrated the Bootstrap Datepicker into my website. I need to customize it so that only specific dates are enabled, including today's date, and all other years, months, and days are hidden from the Datepicker. How can I achieve this? Furth ...

Nextjs - resolving the issue of shopping carts displaying incorrect total amounts

I am currently facing an issue with the total cart amount while building a shopping cart. The problem arises when I visit the cart page as it only displays the amount of the last item added to the cart. state = { cart: { items: [], total: 0 }, }; ad ...

Ensure the filelist resets each time the bootstrap-modal is hidden or closed

Context I am in the process of developing a form where users can input data and upload an image file. The information entered into the form, along with the file name, is stored in a MySQL database. To style the website, I am utilizing Bootstrap. When a u ...

Unable to assign a value to a null property during the onchange event

I'm currently working on a project where I need to display flight details based on the selected flight number. To achieve this, I have created a dropdown menu that lists all available flight numbers and a table displaying various flight details such a ...

Is it possible to establish a delay for requestAnimationFrame()?

My webpage has a very long layout with text in one column and a floating element in another. I want the floating element to follow the scroll of the window and return to its original offset once scrolling stops. The current code I have is: var ticking = ...