The validation feature in ASP.NET MVC does not seem to be functioning properly while using

I'm struggling to make the bootstrap modal and asp.net mvc validation work together seamlessly. My form is quite complex with validation displayed in a bootstrap modal. However, when I press the submit button, the validation doesn't seem to be functioning at all.

The form utilizes standard asp.net mvc validation. Here is a snippet of how it is structured:

@using (Html.BuildForm().AddClass("form-horizontal").Id("contact-add-popup").EncType(FormEncType.MultipartData).Begin()) {
@Html.AntiForgeryToken()
@Html.Partial("_Alerts")
<div class="control-group">

<div class="control-group company-field">
    @Html.BuildLabelFor(m => m.Name).AddClass("control-label")
    <div class="controls">
        @Html.BuildTextBoxFor(m => m.Name).AddClass("input-xxlarge")
        @Html.ValidationMessageFor(m => m.Name)
    </div>
</div>
(...)

Next, here is the structure of my modal:

<div id="createContactModal" class="modal hide fade modal-contact" tabindex="-1" role="dialog" aria-labelledby="createContactModalLabel" aria-hidden="true" data-backdrop="static">
<div class="modal-header">
    <h4 class="modal-label" id="createContactModalLabel">Add contact</h4>
</div>
<div class="modal-body">
    @Html.Partial("_CreateContact", new ContactCreateModel())
</div>
<div class="modal-footer">
    <a href="javascript:$('#contact-add-popup').submit();" class="btn btn-primary">Save</a>
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>

Additionally, I have included some javascript to enable validation within the modal:

        $('#createContactModal').on('shown', function () {
            $("#contact-add-popup").removeData("validator");
            $("#contact-add-popup").removeData("unobtrusiveValidation");
            $.validator.unobtrusive.parse("#contact-add-popup");
        });

        $('#contact-add-popup').on('submit', function(e){
            e.preventDefault();

            $.validator.unobtrusive.parse($("#contact-add-popup"));

            if ($('#contact-add-popup').valid()){
                alert('AJAX');
            }
        }); 

The issue lies in the line if ($('#contact-add-popup').valid()), as it always returns true. What steps can I take to ensure that the modal and validation cooperate effectively?

Answer №1

This method might help you achieve your goal:

let dynamicForm = $("#dynamic-form-popup")
        .removeData("validator")
        .removeData("unobtrusiveValidation");

$.validator.unobtrusive.parse(dynamicForm);

Learn more about dynamic validation here

Answer №2

Through my investigation, I discovered that crucial javascript validation scripts were absent which caused the client-side validation to malfunction. Once these files were added, everything began functioning properly.

I appreciate all the responses provided.

Answer №3

To include this code in the base view, you will need to load a modal and activate client-side validation.

@section scripts {

  @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }

  @* By default, Bootstrap only loads the modal content once. If you want to load different partial views, you will need to clear the existing modal data. *@

  <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>

  <script type="text/javascript">
    $(function () {
      $('#modal-container').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget); // Button that triggered the modal
        var url = button.attr("href");
        var modal = $(this);
        // Activate client-side validation after the page is loaded
        modal.find('.modal-content').load(url, function () {
          $('#registration_form').removeData("validator");
          $('#registration_form').removeData("unobtrusiveValidation");
          $.validator.unobtrusive.parse('#registration_form');
        });
      });
    });
  </script>
}

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

There seems to be an issue with the JSON data format when using Telerik

I'm really puzzled about this issue. Currently, I am developing a page within an application that utilizes Telerik RadGrids. The task seems quite straightforward: each row in the grid has an EditFormSettings Template set up. Inside this template, the ...

Providing data from a javascript xml file upon page initialization

I am aiming to extract multiple values from an XML file as soon as an HTML page is loaded. The XML file remains constant and will not change over time. It will be stored in the same directory as the HTML page. The purpose of this XML file is to fill severa ...

Reducing the number of DOM manipulations for websites that heavily utilize jquery.append

Here's a snippet of my coding style for the website: !function(){ window.ResultsGrid = Class.extend(function(){ this.constructor = function($container, options){ this.items = []; this.$container = $($container); ...

Click on each item within the v-for loop to gather relevant information, and subsequently iterate through the collected data

Within a v-for loop, I have implemented a button that, when clicked, retrieves specific data. The objective is to display this data below or in place of the clicked button. <div v-for="(item, index) in items" :key="index"> <button @click="fetch ...

Activate the Alert (https://material-ui.com/components/alert/#alert) starting from the React component at the bottom of the hierarchy

When it comes to alerts, a normal alert is typically used like alert("message to be displayed");. However, I prefer using material UI Alerts which return a JSX component. For example: <Alert severity="success">This is a success alert — check it out ...

Activate divs with Bootstrap5 modal toggle functionality

What adjustments must be made to the Bootstrap 5 example below in order to achieve the following two objectives: The "afterAcceptingTerms" division should remain hidden until the user clicks on the Accept Terms modal button, ensuring that only the "before ...

casperjs timeout issue with an endless loop

Currently, I am utilizing casperjs to retrieve the content of a website that updates its values using websockets. Rather than attaching an event listener to each value, my goal is to scrape the entire website every 10 seconds. Here is the code snippet I a ...

Adjust the height of each card dynamically based on the tallest card in the row

I am working on a row that looks like this: <div class="row"> <div class="col"> <div class="card"> <div class="card-body"> <h3 class="card-title ...

Modifying a CSS property with jQuery

If I have the following HTML, how can I dynamically adjust the width of all "thinger" divs? ... <div class="thinger">...</div> <div class="thinger">...</div> <div class="thinger">...</div> ... One way to do this is usi ...

Ways to troubleshoot issues that arise when updating the node version

After upgrading my version, I encountered a serious error. I developed a program a few years ago using version 18.x. Now that I have upgraded node.js, I am facing some errors. Below are the error messages: ERROR in ./app/assets/scss/styles.scss (./node_mo ...

Determine the Size of an Image File on Internet Explorer

Is there an alternative method? How can I retrieve file size without relying on ActiveX in JavaScript? I have implemented an image uploading feature with a maximum limit of 1 GB in my script. To determine the size of the uploaded image file using Java ...

Enter the event title in the form to display it

I am looking to create a unique navigation bar form, where users need to enter event.title to access the event show page. Here is an example of how it should appear: https://i.sstatic.net/gpaYo.png The code for the form is as follows: %form.form-inli ...

Modify the array value and access it outside of an asynchronous function

Is there a way to set values in an array from an asynchronous function and access it outside of that function's scope? I am working on a project where I need to randomize values in an array, so that I can assign images randomly to different div eleme ...

Vue not displaying local images

I'm having trouble creating an image gallery with Vue.js because local images are not loading. I have the src attributes set in the data attribute and can only load images from external sources. For example: data() { return { imag ...

Constructing a form by employing the directive approach to incorporate various input fields

My goal is to create input fields that capture information when the submit button is clicked using the directive method. These values will then be passed as arguments to a function. However, my current code is not functioning as expected. <!DOCTYPE htm ...

Using Testcafe to extract the value attribute of a hidden input element

Is there a way to retrieve the value of an <input>, especially what is contained within its value attribute even if the input is not visible? I am using testcafé, but it seems like this could be a challenge. Does anyone have any suggestions or opti ...

Cookie vanished post registration in the captive portal

Just a heads up, I'm new to this. I've encountered an issue where a cookie doesn't persist after captive portal login. The setup involves landing on our web server, storing MAC and a unique ID on two cookies, redirecting for authentication, ...

Two objects intersecting in space

When using AngularJS for insert and update operations, I encounter a problem where changes made to user data are reflected in the list of users. Additionally, when adding a new user, the last record's data populates all input fields. Code: User List ...

Troubleshooting: 404 Error When Trying to Send Email with AJAX in Wordpress

In the process of creating a unique theme, I encountered an interesting challenge on my contact page. I wanted to implement an AJAX function that would allow me to send emails directly from the page itself. After conducting some research, I managed to find ...

How to toggle between checked and unchecked states using jQuery within AngularJS?

After reloading, the checkbox should maintain its checked or unchecked state. This functionality can be achieved using a directive controller. var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {}, $checkboxes = $("#c ...