Using jQuery: What is the best way to implement form validation in jQuery before submitting?

I've created a Bootstrap form as shown below:

<form id="loginForm" method="post" action="" role="form" class="ajax">
   <div class="form-group">
       <label for="userName"></label>
       <input type="text" class="form-control" id="usrName">
    </div>

   <div class="form-group">
       <label for="passWrd"></label>
       <input type="password" class="form-control" id="passWrd">
    </div>

   <div class="form-group">
       <button class="btn btn-default" type="button" id="loginButton">Login</button>      
    </div>

In my jQuery code, I am handling form validation. How can I trigger the submit() method to make an AJAX call and submit the form after validation?

$(document).ready(function() {

  function validateInput(id) {
    if($("#"+id).val()==null || $("#"+id).val()=="") {
      var div=$("#"+id).closest("div");
      div.addClass("has-error");
      return false;
    } else {
      var div=$("#"+id).closest("div");
      div.removeClass("has-error");
      div.addClass("has-success");
      return false;
    }     
  }
  $(#loginButton).click(function() {

    if(!validateInput("userName"))
    {
      return false;
    }

    if(!validateInput("passWrd"))
    {
      return false;
    }

  });

});

How can I implement the ajax call after completing the validation in the above code snippet?

Note: I am not allowed to use any external jQuery plugins for validation.

Answer №1

When you use $('#loginForm').submit()
, the form will be submitted.

Answer №2

Here is a suggestion:

$(document).ready(function() {
  function checkInput(id) {
  var target = $("#"+id);
  var passed = false;
    if (target.val() == null || target.val().trim() == "") {
      target.closest("div").addClass("has-error");
    } else {
      var container = target.closest("div");
      container.removeClass("has-error");
      container.addClass("has-success");
      passed = true;
    }     
  return passed;
  }
  $(#loginButton).click(function() {
    if (checkInput("usrName")) {
         $('#loginForm').submit()
    }
  });

});

Answer №3

<div ng-class="{ 'form-group has-error has-feedback' : datos.campo.$invalid && !datos.campo.$pristine, 'form-group has-success has-feedback' : datos.campo.$valid}">
    <label class="control-label" for="campo">Modelo</label>
        <input ng-model="data.campo" name="campo" type="text" class="form-control" id="campo" required>
        <span ng-class="{'glyphicon glyphicon-remove form-control-feedback':datos.campo.$invalid && !datos.campo.$pristine, 'glyphicon glyphicon-ok form-control-feedback':datos.campo.$valid}"></span>
    <span ng-show="datos.campo.$invalid && !datos.campo.$pristine" class="col-md-8 center badge badge-danger">Incorrecto</span>
</div>

Usando Angular JS se simplifica enormemente la validación de campos, Echa un vistazo a este enlace

Answer №4

This script is designed to validate every input field on the page.

$(#loginButton).click(function() {
  if (!$.trim($("input").val()) {     //checking ALL input fields for valid values
    alert("Some inputs need attention!");
  } else {
    submit();  //triggering submission as indicated in your query
    $.ajax({});//or make an ajax request, or encapsulate it within a function and invoke it - various options are available.
  }
});

Answer №5

There are various ways to achieve this, but based on your approach, it seems that you already have a mechanism in place where you return false if validation fails. To improve on this, simply make sure to return true at the end of your validateInput() method.

function validateInput(item) {
  var container = item.closest("div");
  if (item.val() == null || item.val() == "") {        
    container.addClass("has-error");
    return false;
  } else {
    container.removeClass("has-error");
    container.addClass("has-success");
    return true;
  }
}

Afterwards, within the click event handler, evaluate the result from validateInput() and proceed with form submission if all checks pass.

$('#loginButton').click(function() {
  var isValid = true;
  $('.form-control').each(function(){
      isValid &= validateInput($(this));
  });
  if (isValid)
  {
      var formData = $('#loginForm').serialize();
      $.ajax({
         url: 'your API endpoint',
         type: 'POST',
         data: formData
      });
  }
});

This will allow you to properly submit the form once all required fields have been validated.

For a live demo, check out this example link.

Answer №6

If you're looking for a reliable form validation solution, I highly recommend checking out this plugin. In my experience, it has been the most effective and user-friendly option available.

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

Making a CSS table fit perfectly inside a container

After reading numerous recommendations on the subject, none of them seem to be effective in my particular situation. The issue lies with a table that is nested within a container ('div' element) as shown below: <div class="container"> ...

Modifying the Vue.js Vue3-slider component for custom color schemes

Currently, I am using the vue-slider component and would like to customize the color of the slider itself. The specific class that needs to be styled is "vue-slider-dot-tooltip-inner". Below is a screenshot displaying the original CSS styling for vue-slid ...

The 'utf-8' codec is unable to interpret the byte 0x96 at position 227, as it is an invalid start byte

Recently, I began working with Django. Unfortunately, I encountered an error that I haven't been able to solve. Can anyone explain why this error is occurring? Specifically, I am utilizing {% extends "base.html" %} on my login page. Here is the exa ...

Incorporating a HTML layout with a JS backdrop

I have successfully implemented a JavaScript background and now I want to apply this background across all my PHP files. The issue is that the HTML code either overlaps with the JS content or appears behind it. How can I resolve this? Below is the JS fil ...

What is the best way to retrieve key/value pairs from a JSON object?

After making a call to an external service, I receive a domain object in return: var domainObject = responseObject.json(); This JSON object can then be easily accessed to retrieve specific properties. For example: var users = domainObject.Users The &ap ...

Can a custom javascript object be exported in various formats similar to the Date object?

Consider the following scenario where I have a custom object: function MyObject(a, b){ this.prop = a; this.name = b; this.doSomething = function(){ return "something"; } } var a = new MyObject(4, 'name'); I am looking fo ...

What is the best way to reveal a concealed "div" when hovering the mouse over it?

Currently in the process of developing a dropdown menu to house a search engine form within a static menu bar. The desired functionality is for the search form to appear upon hovering over the "search icon." However, it seems that the submenu fails to disp ...

Mixing box-shadow and blur filters can result in unusual artifacts appearing in Webkit browsers

Recently, I encountered an intriguing and frustrating bug in WebKit browsers. Consider a scenario where there is a parent DIV (let's say .wrapper) and a child DIV (.main). You apply a box-shadow on the .main DIV and a blur filter on the .wrapper DIV. ...

Adjusting the sizes of images with varying aspect ratios to perfectly fit within a div without distorting its shape

I'm currently in the process of developing my portfolio website and I am faced with creating a simplistic image browser feature. My goal is to have a container div that adjusts in size according to the browser window, allowing it to house images of va ...

Adjusting the demonstration of the d3 force-directed graph

Recently, I have started learning about javascript and D3.js, and I am eager to grasp their functionalities. My current focus is on experimenting with the force-directed graph example available at: http://bl.ocks.org/mbostock/4062045 My goal is to modify ...

Is it possible to eliminate the black bars from YouTube HQdefault image using only CSS?

(After searching extensively, I couldn't find the exact same question and answer) I have a dilemma with displaying YouTube's hqdefault thumbnails on my page. It seems that they are 480 by 360 pixels, resulting in black bars at the top and bottom ...

Encountering iOS 10 freezing issues when scrolling through an HTML list that is styled with -webkit-overflow-scrolling: touch

Overview This specific issue pertains to a potential freeze that occurs when scrolling through a <ul /> element that has been styled using CSS, specifically with the property -webkit-overflow-scrolling: touch on the Safari browser of iOS. Related Pr ...

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 ...

Creating an AngularJS directive with the help of the angular.module function

Could someone please help me understand why I am getting an "Argument 'MainCtrl' is not a function, got undefined" error? It seems to be related to module dependency injection when using directives. angular.module('app', []) .control ...

Component that dynamically changes background images in Vue

I'm currently working on a Vue banner that requires a dynamic background, but for some reason, it's not functioning as expected. I've experimented with different methods, and using an image tag like this works: <img :src="require(`@/asse ...

Unleashing the Power of Object Destructuring in React Hooks

Here is a straightforward code snippet: import React from "react"; import { useForm } from "react-hook-form"; export default function App() { const { register, formState: { errors }, handleSubmit } = useForm(); return ( < ...

Calculating the Bounding Box of SVG Group Elements

Today I encountered a puzzling scenario involving bounding box calculations, and it seems that I have yet to fully understand the situation. To clarify, a bounding box is described as the smallest box in which an untransformed element can fit within. I h ...

Clicking the button to send the form using JavaScript

Currently, I am dealing with a shopping cart plugin that relies on a basic form on the product page to send values such as price and product name. However, I am facing an issue where this plugin uses a standard submit button to transmit the values, and I w ...

Using AJAX to send arguments to Eloquent in Laravel

Currently working on a Laravel application where I am attempting to retrieve Ajax data upon clicking a link within a table cell. My objective is to pass a parameter for use in an Eloquent query. Below is the JavaScript code: $('#monthly_table tbody&a ...

Retrieve Static Property Values Using jQuery/JavaScript in Backend Code

My challenge is to fetch the Max value and Percent value into a jQuery function. I attempted to retrieve these values using hidden variables and Session variables on page load, but they always return 0. Here are the properties: public static int Max { ...