Jquery Validation is not functioning properly in MVC using C#

I have been working on an MVC App and am currently trying to determine if a user is registered. To achieve this, I have created a model:

public class Ejemplo
 {
   [Required(ErrorMessage="Please specify Username")]
   [DataType(DataType.Text)]
   public string usuario { get; set; }

   [Required(ErrorMessage="Please specify password")]
   [DataType(DataType.Password)]
   public string password { get; set; }
 }

My current issue lies in sending the user information in a JSON format through AJAX and needing to validate that the username and password are specified. In order to address this, I have written the following code:

<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
    <script type="text/javascript">
    $(document).ready(function () {

        $('#myform').validate({ 
            rules: {
                usuario: {
                    required: true,
                    minlength: 12
                },
                password: { required: true }
            },
            messages: {
                usuario: {
                    required: "You must specify a username - please validate!!!",
                    minlength: "Invalid length - please validate!!!"
                },
                password: {
                    required: "You must specify a password - please validate!!!"
                }
            },
             submitHandler:
                    $("#myform").on('submit', function () {
                        alert("Have just pressed submit");
                        if ($("#myform").valid()) {
                            alert("Here is some code inside $.AJAX({})");
                        }
                        return false;
                    })
        })
    });

This is my form (the code above and the form are in the same file: Index.cshtml)

<fieldset>
 <legend> MVC Validations </legend>
  @using (Html.BeginForm("Prueba", "Prueba", FormMethod.Post, new { @id = "myform" }))
  {

     @Html.LabelFor(M => M.usuario);
     <br />
     @Html.EditorFor(M=>M.usuario)
     @Html.ValidationMessageFor(M => M.usuario);
     <br />
     @Html.LabelFor(M=>M.password)
     <br />
     @Html.EditorFor(M=>M.password);
     @Html.ValidationMessageFor(M=>M.password)
     <br />
     <br />

  <input type="submit" id="boton_id" name="boton_name" value="Submit" />
                }
        </fieldset>

However, the validation does not work and no message appears if the username and password fields are left empty. Only the initial alert is shown: alert("Have just pressed submit"); but the second alert never shows up: alert("Here is some code inside $.AJAX({})"); these two alerts are within

submitHandler:
                    $("#myform").on('submit', function () {
                        alert("Have just pressed submit");
                        if ($("#myform").valid()) {
                            alert("here is some code inside $.AJAX({})");
                        }
                        return false;
                    })

If you could provide assistance in identifying where the problem lies or what I may be missing, it would be greatly appreciated.

Answer №1

Firstly, your JavaScript code for invoking the validate function is not written correctly. You must encapsulate the code for submitHandler within a function:

submitHandler: function () { .... }

Additionally, the submitHandler function is automatically triggered when the submit event occurs (and when the form is valid). It is unnecessary to attach another event handler or validate the form's validity within the submitHandler.

As per the details in the official documentation:

This callback functions specifically for managing the actual submission process upon successful validation of the form. Receives the form as the sole argument. Replaces the default submission method. The recommended spot for making an Ajax submission after validating the form.

The following revised code should be sufficient:

submitHandler: function () {
    // Submitting the form via AJAX.
}

Answer №2

In response to @AndrewWhitaker's comment, I would like to provide some additional information:

Perhaps removing unobtrusive validation could resolve any conflicts.

The issue lies in the fact that jquery.validate.unobtrusive.js internally creates a validator and links it to the form. When you initialize the plugin with the code below:

$(document).ready(function () {
    $('#myform').validate({ // initialize the plugin

jquery.validate.js essentially performs the following actions:

validate: function( options ) {
    ...
    var validator = $.data(this[0], 'validator');
    if ( validator ) {
        return validator;
    }

It simply checks for an existing validator linked to your form and returns it, rendering your initialization settings ineffective in this scenario.

Instead of removing jquery.validate.unobtrusive.js (unless unnecessary), you can directly access and modify the validator settings, for example:

var validator = $('#myForm').validate();
validator.settings.submitHandler = function(form) { ...
// etc.

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

Reference to children of jQuery DOM object

To improve the quality of my code, I am attempting to write event handler functions that are able to identify their source. It's unclear whether my approach is incorrect or if the nesting of divs within tables on the page is causing issues. The objec ...

Navigating Up a Directory with JQuery

Is there a way to navigate up one directory level in my jQuery code? The code below is referencing a folder named "uploads" on the C drive, but I can't find any mention of "uploads" in my HTML. How does it know to look there? And how can I go back to ...

Identify when two calendar dates have been modified

Creating a financial report requires the user to select two dates, search_date1 and search_date2, in order for a monthly report to be generated. Initially, I developed a daily report with only one calendar, where I successfully implemented an AJAX script ...

What is the reason for needing a page reload in Javascript or JQuery?

I'm curious why Javascript or jQuery require a page reload before applying certain effects. CSS updates in real-time, as demonstrated by the following example: This changes dynamically without needing to refresh the page @media all and (max-width:7 ...

The fancybox scroll feature is visible when using a browser, but unfortunately, it does not appear on the

I noticed that the scrollbar in my fancybox is not showing up on iPad, but it does display when using Google Chrome on Desktop. You can find the page here. The issue seems to be with the vertical scroll bar not appearing on iPad. Has anyone encountered th ...

Designing a file upload progress bar with the help of jquery and ajax

I am looking to implement a progress bar for uploading files utilizing jquery and ajax. Here is the jquery code I have written: function updateProgress(evt) { // evt is an ProgressEvent. if (evt.lengthComputable) { var percentLoaded = ...

How to switch between classes for elements and return to the original one when none of the elements is chosen

Hello there, I need some assistance. Here's the scenario: I am working with a grid of six items. My goal is to have the first item in the grid become active by default. When the user hovers over any of the remaining five items, I want the active clas ...

JQuery Challenge: Solving Dynamic Modal Issues

I'm in the process of creating a webpage that features multiple divs, each with its own unique image and title. Within each div, there's a button that, when clicked, should grab the specific image and title and display them in a modal. However, I ...

Submitting a page with PHP, Ajax, and JSON

Need help with making an Employee search functionality in my business using Ajax. After submitting the form, I want to load employee details using jQuery-based Ajax. Here is the code for searching employees. The problem I'm facing is that after submi ...

Using jQuery, you can store values in a PHP array or session by making an AJAX

Is there a way to store values in PHP array or PHP session using ajax in jQuery? I am trying to send some values via ajax to a PHP page and store them. The issue is that every time the array/session only returns the latest sent value, and not the previous ...

Utilize setState to showcase data fetched from AJAX request

Currently, I am in the process of developing a web application using the GitHub search API. My goal is to have detailed information about each repository displayed below its corresponding entry. Specifically, I want the content retrieved from the AJAX re ...

IE Troubles: Timer Function Fails in Asp.Net MVC

I implemented the following code snippet: @Using Ajax.BeginForm("Index", New AjaxOptions() With { _ .UpdateTargetId = "AnswerSN", .HttpMethod = ...

Employing jQuery to redirect to a different URL when a button is clicked

I've been experimenting with a project that involves both JQuery and AJAX. One of the features I have added is JQuery autofill. Here is the code snippet for the form: <form class="form-horizontal"> <div class="form-group"> < ...

Validate Bootstrap - Transmit data from all form fields to external PHP script

Is there a way to send all input field values to a remote PHP file using Bootstrap Validator? In my log in form, I have two input fields. I'm utilizing Bootstrap Validator's remote validation on both of them. However, each validation only sends ...

Soft keyboard on mobile fails to update when arrows are used in Ajax-populated dropdown menus

I am working on a web form that includes two select fields: Country and City: <select id="country" onchange="getCity(this);"> <option value="">-- Please select your country --</option> <option value="1">Austria& ...

Implementing an inline cache for <script> tags that load AJAX content

Looking for a way to cache <script src> received through AJAX requests? Currently, each call attempts to load the src via AJAX by default. However, the issue is that this script remains constant throughout the session and only needs to be re-evaluate ...

What is the best way to animate my logo using JavaScript so that it scales smoothly just like an image logo

I dedicated a significant amount of time to create a unique and eye-catching logo animation for my website! The logo animation I designed perfectly matches the size of the logo image and can be seamlessly integrated into the site. The issue arises when th ...

Restricting Entry to a NodeJS Express Route

Currently, I am in the process of developing an express project where I have set up routes to supply data to frontend controllers via ajax calls, specifically those that start with /get_data. One issue I am facing is how to secure these routes from unauth ...

Unleashing the potential of extracting the value of a subsequent iteration while within the

Currently, I am facing a dilemma as I am unable to comprehend the logic required to design this algorithm. The problem at hand involves a sequence of images with arrows placed alternatively between each image. The structure appears as follows: Image -> ...

Autocomplete feature enhanced with the ability to validate and clear out

Here's a snippet of my HTML code: <div class="form-group"> <label for="date_chargement" class="col-sm-4 control-label">Minimum loading date:</label> <div class="col-sm-2"> <input type="text" class="form-control te ...