DEVHIDE
  • Home (current)
  • About
  • Contact
  • Cookie
  • Home (current)
  • About
  • Contact
  • Cookie
  • Disclaimer
  • Privacy
  • TOS
Login Or Sign up

FormValidation on modal bootstrap

3.9k Views Asked by Code Ratchet At 20 June 2015 at 07:59 2025-12-23T19:11:47.075000

I have a modal as so

<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h2 class="page-title">
                Add Movie
                <small>Note fields marked with <span style="color:red">*</span> are required</small>
            </h2>
        </div>
        <div class="modal-body">
            <form class="form-horizontal" role="form" id="NewMovie">
                <div class="form-group">
                    <label class="control-label col-sm-4" for="prefix">
                        Title <span style="color:red">*</span>
                    </label>
                    <div class="col-sm-6">
                        <input type="text" class="form-control" id="Title" name="Title" />
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-4" for="prefix">
                        Classification <span style="color:red">*</span>
                    </label>
                    <div class="col-sm-6">
                        <input type="text" class="form-control" id="Classification" name="Classification" />
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-4" for="prefix">
                        Rating <span style="color:red">*</span>
                    </label>
                    <div class="col-sm-6">
                        <input id="Rating" name="Rating" data-slider-id='ex1Slider' type="text" data-slider-min="0" data-slider-max="5" data-slider-step="1" data-slider-value="0" /> <span id="rate" style="margin-left:5%">0 / 5</span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-4" for="prefix">
                        Release Date <span style="color:red">*</span>
                    </label>
                    <div class="col-sm-6">
                        <input type="text" class="form-control" id="ReleaseDate" name="ReleaseDate" />
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-4" for="prefix">
                        Cast <span style="color:red">*</span>
                    </label>
                    <div class="col-sm-5">
                        <input type="text" class="form-control col-sm-5" id="Cast" />
                    </div>
                    <div class="col-sm-1">
                        <button type="button" id="btnNewCast" class="btn btn-default">+</button>
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-4" for="prefix"></label>
                    <div class="col-sm-6" id="newCast">
                    </div>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" id="btnAddMovie" data-dismiss="modal">Save</button>
        </div>
    </div>

</div>

When btnAddMovie is clicked I ajax / jquery method is called which calls a method in my controller. But before I submit I would like to validate the fields they have entered.

I am following this Form validation on bootstrap modal

I have declared my implementation as follows:

$(document).ready(function() {
$('#NewMovie').formValidation({
    framework: 'bootstrap',
    excluded: [':disabled'],
    icon: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        Title: {
            validators: {
                notEmpty: {
                    message: 'The Title is required'
                }
            }
        }
    }
});
});

My ajax method is as follows:

$("#btnAddMovie").click(function () {

            var stringArr = $('span[data-id="cast[]"]').map(function () {
                return $(this).text().trim();
            }).get();

            $.ajax({
                url: '/Movies/Add',
                traditional: true,
                data: { "Title": $("#Title").val(), "Classification": $("#Classification").val(), "Rating": $("#Rating").val(), "ReleaseDate": $("#ReleaseDate").val(), "Cast": stringArr },
                cache: false,
                type: "POST",
                success: function (result) {
                    if (result.success) {

                    }
                },
                error: function (result) {
                    alert("Error");
                }
            });
        });

But for some reason when ever click the button on my form it automatically posts back without doing the validation?

I'm trying to validate and depending on if its true or false then perform the relevant action.

javascript jquery formvalidation-plugin
Original Q&A
2

There are 2 best solutions below

0
Arkni Arkni On 20 June 2015 at 14:05 BEST ANSWER

About your button, either you have to change it to a submit button or use the button setting to indicate which button should trigger the validation (see bellow)

button: {
    // The submit buttons selector
    selector: '#btnAddMovie'
}

you have to delete data-dismiss="modal" from your button

And then trigger the success.form.fv event and call your ajax method there, see following code:

$('#NewMovie').formValidation({
    framework: 'bootstrap',
    excluded: [':disabled'],
    // ...
    icon: {
        // ...
    },
    fields: {
        // ...
    }
})
.on('success.form.fv', function(e) {
    // Prevent form submission
    e.preventDefault();

    // And then
    // Place your Ajax call here
    var stringArr = $('span[data-id="cast[]"]').map(function () {
        return $(this).text().trim();
    }).get();

    $.ajax({
        url: '/Movies/Add',
        traditional: true,
        data: { "Title": $("#Title").val(), "Classification": $("#Classification").val(), "Rating": $("#Rating").val(), "ReleaseDate": $("#ReleaseDate").val(), "Cast": stringArr },
        cache: false,
        type: "POST",
        success: function (result) {
            if (result.success) {

            }
        },
        error: function (result) {
            alert("Error");
        }
    });

    // And then close your modal
    $('#MyModal').modal('hide');
});

# References:

  • form events docs: http://formvalidation.io/settings/#event-form
  • button setting docs: http://formvalidation.io/settings/#form-button
0
DFayet DFayet On 20 June 2015 at 09:54

If you remove your ajax call, does the validation work?

Maybe you should take a look at your submit button :

<button type="button" class="btn btn-default" id="btnAddMovie" data-dismiss="modal">Save</button>

which is not a submit button.

If you look to the example in the page you gave us, you can see that the submit button's code is

<button type="submit" class="btn btn-primary">Login</button>

Try to change this and it would be nice if you could provide us a JSFiddle

Hope it's gonna help you a bit.

Related Questions in JAVASCRIPT

  • Using Puppeteer to scrape a public API only when the data changes
  • inline SVG text (js)
  • An array of images and a for loop display the buttons. How to assign each button to open its own block by name?
  • Storing the preferred font-size in localStorage
  • Simple movie API request not showing up in the console log
  • Authenticate Flask rest API
  • Deploying sveltekit app with gunjs on vercel throws cannot find module './lib/text-encoding'
  • How to request administrator rights?
  • mp4 embedded videos within github pages website not loading
  • Scrimba tutorial was working, suddenly stopped even trying the default
  • In Datatables, start value resets to 0, when column sorting
  • How do I link two models in mongoose?
  • parameter values only being sent to certain columns in google sheet?
  • Run main several times of wasm in browser
  • Variable inside a Variable, not updating

Related Questions in JQUERY

  • In Datatables, start value resets to 0, when column sorting
  • Bootstrap modal not showing at the desired position on a web page when the screen size is smaller
  • window.location.href redirects but is causing problems on the webpage
  • Using JQuery Date Slider
  • Storing selected language in localStorage
  • How to stop other divs from still showing when i click a different button?
  • Check multiple values with jQuery
  • Bootstrap component does not want to render in Datatables function
  • put white spaces when entering an amount moneytype symfony
  • Trouble accessing custom header in AJAX response using jQuery in Fiware Keyrock
  • I just cant make it work, HTML, JS and Firebase error
  • Didn't declared variable still not getting any error in JavaScript
  • Move element horizontally while scrolling vertically in pure JavaScript
  • allow multi carousel in same page
  • Embedded TikTok posts / thumbnail styling issue

Related Questions in FORMVALIDATION-PLUGIN

  • How to add timeout or debouncing in formvalidation - validations will occur after the user enters data into the input field
  • How to integrate FormValidation's external plugins with Metronic?
  • Form Validation Prompt after .api response - Semantic Ui
  • I want an alert box to be displayed and after that my input field to stay on focus when it's value is empty
  • laravel 9: how to make validation for $jumlahcuti > $sisacuti before the form is submitted
  • jquery validation plugin detects errors, but no messages appear, why not?
  • Does the FormValidation Plugin free
  • How do I change the "This field is required" validation message Jquery
  • angular 13 form validation dynamic input textbox show error on touch
  • How does form field validation occur on a Magento Checkout page
  • how to properly use Veulidate along with vuex in vue 2
  • Validate form before Stripe pop up/payment modal appears
  • Set Function as Compare in Form Validation using Declarative plugin
  • Multiple File Upload using dropzone and with other forms fields with FormValidation plugin
  • Laravel form validation set rules like first two character are alphabet and last four character numeric like AB1234

Trending Questions

  • UIImageView Frame Doesn't Reflect Constraints
  • Is it possible to use adb commands to click on a view by finding its ID?
  • How to create a new web character symbol recognizable by html/javascript?
  • Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
  • Heap Gives Page Fault
  • Connect ffmpeg to Visual Studio 2008
  • Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
  • How to avoid default initialization of objects in std::vector?
  • second argument of the command line arguments in a format other than char** argv or char* argv[]
  • How to improve efficiency of algorithm which generates next lexicographic permutation?
  • Navigating to the another actvity app getting crash in android
  • How to read the particular message format in android and store in sqlite database?
  • Resetting inventory status after order is cancelled
  • Efficiently compute powers of X in SSE/AVX
  • Insert into an external database using ajax and php : POST 500 (Internal Server Error)

Popular # Hahtags

javascript python java c# php android html jquery c++ css ios sql mysql r reactjs node.js arrays c asp.net json

Popular Questions

  • How do I undo the most recent local commits in Git?
  • How can I remove a specific item from an array in JavaScript?
  • How do I delete a Git branch locally and remotely?
  • Find all files containing a specific text (string) on Linux?
  • How do I revert a Git repository to a previous commit?
  • How do I create an HTML button that acts like a link?
  • How do I check out a remote Git branch?
  • How do I force "git pull" to overwrite local files?
  • How do I list all files of a directory?
  • How to check whether a string contains a substring in JavaScript?
  • How do I redirect to another webpage?
  • How can I iterate over rows in a Pandas DataFrame?
  • How do I convert a String to an int in Java?
  • Does Python have a string 'contains' substring method?
  • How do I check if a string contains a specific word?

Copyright © 2021 Jogjafile Inc.

  • Disclaimer
  • Privacy
  • TOS
  • Homegardensmart
  • Pricesm.com
  • Aftereffectstemplates