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-03T03:04:54.326000

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

  • Angular Show All When No Filter Is Supplied
  • Why does a function show up as not defined
  • I count the time the user takes to solve my quiz using Javascript but I want the same time displayed on another page
  • Set "More" "Less" font size
  • Using pagination on a table in AngularJS
  • How to sort these using Javascript or Jquery Most effectively
  • how to fill out the table with next values in array with one button
  • State with different subviews
  • Ajax jQuery firing multiple time display event for the same result
  • Getting and passing MVC Model data to AngularJS controller
  • Disable variable in eval
  • javascript nested loops waiting for user input
  • .hover() seems to overwrite .click()
  • How to sort a multi-dimensional array by the second array in descending order?
  • How do I find the fonts that are not loading in a CORS situation ( MoovWeb )?

Related Questions in JQUERY

  • How to sort these using Javascript or Jquery Most effectively
  • Ajax jQuery firing multiple time display event for the same result
  • .hover() seems to overwrite .click()
  • Check for numeric value with optional commas javascript
  • Extending Highmaps Side Effect
  • Array appending after each onclick and loop in javascript
  • how can i append part of a table based on how many tr it has?
  • Play multiple audio files in a slider
  • Remove added set of rows
  • Access property of an object of type [Model] in JQuery
  • AJAX PHP - Reload div after submit
  • proengsoft/laravel-jsvalidation ReferenceError: jQuery is not defined
  • when a checkbox is checked how to display a different hidden element using javascript
  • Get jquery error Uncaught RangeError: Maximum call stack size exceeded
  • Removing only the closest thead on table filtering

Related Questions in FORMVALIDATION-PLUGIN

  • formvalidation use two regex pattern
  • formvalidation how to use remote only when needed
  • revalidateField not working
  • How to dynamically change validators at runtime
  • Adding a custom function to formValidation.js configuration
  • FormValidation on modal bootstrap
  • Submit button gets disable after deleting tr
  • how to customize Jquery form Validator method and and a specific khmer unicode
  • How does form field validation occur on a Magento Checkout page
  • angular 13 form validation dynamic input textbox show error on touch
  • Regex validation by equal number of vowels and consonants
  • how to trim non required field before validating it in javascript
  • How can remove error message when i re correct my input value?
  • inserting data to mysql table from bootstrap dynamic fields
  • laravel 9: how to make validation for $jumlahcuti > $sisacuti before the form is submitted

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

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
  • Math
  • Aftereffectstemplates