FormValidation on modal bootstrap

3.9k views Asked by At

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.

2

There are 2 answers

0
Arkni On 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:

0
DFayet On

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.