Write Down
Write Down

Reputation: 156

Bootstrap 3 form modal, using PHP, validation

I'm trying to use the Bootstrap 3 modal function. I created a simple form within the modal. enter image description here

My aim is that the form is processed with PHP, wich I managed with the following script:

$(function() {
    $("button#submit").click(function() {
        $.ajax({
            type: "POST",
            url: "process.php",
            data: $('form.company').serialize(),
            success: function(response) {
                var result = jQuery.parseJSON(response);
                /* TO DO */
                if (result.success === 0) {
                    $("#error").html(response);
                    $("#error").show();
                } else {
                    $("#success").html(response);
                    $("#success").show();
                    $("#myModal").modal('hide');
                }
            },
            error: function() {
                alert("failure");
            }
        });
    });
});

This is working quite good, I'm able to add the new created company to the database and so on. The input is checked server-side and if it is not okay, the user gets an error (currently not fully implemented, but the idea is working). The problem is, I would like to show to the user that some fields are not okay, instead of just a global error message (#error).

I found out that jQuery has a form validation option, but I can't get it working for some reason. And last but not least, I would like to create a multilanguage application. So, another problem is that I should be able to change the error messages produced by the jQuery validation method. (I would like to pass those messages from my process.php script).

Here is the code of the form:

<form class="form-horizontal company" role="form" id="comp">
                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">Name</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="name" name="name" placeholder="Company">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="street" class="col-sm-2 control-label">Street</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="street" name="street" placeholder="Street">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="number" class="col-sm-2 control-label">Number</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="number" name="number" placeholder="Number">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="zipcode"  class="col-sm-2 control-label">ZIP Code</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="zipcode" name="zipcode" placeholder="ZIP Code">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="city" class="col-sm-2 control-label">City</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="city" name="city" placeholder="City">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="country" class="col-sm-2 control-label">Country</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="country" name="country" placeholder="Country">
                        </div>
                    </div>
                </form>

This is the script that I tried for the validation: http://jsfiddle.net/v5HQr/1/

Someone could advise me?

Upvotes: 1

Views: 15351

Answers (1)

oceanexplorer
oceanexplorer

Reputation: 1229

To get validation to work properly I had to associate the bootstrap classes with jQuery. Try adding the following defaults for jQuery, suggest you place it at the top of your JavaScript file.

if (jQuery.validator) {
    jQuery.validator.setDefaults({
        debug: true,
        errorClass: 'has-error',
        validClass: 'has-success',
        ignore: "",
        highlight: function (element, errorClass, validClass) {
            $(element).closest('.form-group').addClass('has-error');
        },
        unhighlight: function (element, errorClass, validClass) {
            $(element).closest('.form-group').removeClass('has-error');
        },
        errorPlacement: function (error, element) {
            $(element).closest('.form-group').find('.help-block').text(error.text());
        },
        submitHandler: function (form) {
            if ($(form).valid()) {
                form.submit();                    
            }
            else {
              return false;
            }
        }
    }
});

}

HTML

You will also need to include the required markup on your inputs, for example:

<form>
    <input required>
</form>

You can also add data attributes as well, this site has a list to get you started:

http://denverdeveloper.wordpress.com/2012/09/26/some-things-ive-learned-about-jquery-unobtrusive-validation/

data-val=”true” enable unobtrusive validation on this element (should be on every input element you want to validate)
data-val-required=”ErrMsg”  makes the input required, and shows the ErrMsg
data-val-length=”ErrMsg” 
data-val-length-min=”5” 
data-val-length-max=”15”    sets required string length and associated error message.
data-val-number=”ErrMsg”    makes a field required to be a number.
data-val-date=”ErrMsg”  requires a field to be a date (I do not recommend this, as it accepts too much – I prefer to use regex).
data-val-equalto=”ErrMsg” 
data-val-equalto-other=”Fld”    requires one field to match the other (such as password confirm.  Fld is a jQuery selector
data-val-regex=”ErrMsg” 
data-val-regex-pattern=”^regex$”    Requires the field to match the regex pattern.
data-val-email=”ErrMsg” requires a field to be a email (I do not recommend this, as it accepts too much – I prefer to use regex).
data-val-url=”ErrMsg”   requires a field to be a url (I do not recommend this, as it accepts too much – I prefer to use regex).

As I noted – several things, url , phone, email, date you might find work better with regex. Here are some of the regex’s I have used:

number  ^(\d{1,3},?(\d{3},?)*\d{3}(\.\d{1,3})?|\d{1,3}(\.\d{2})?)$
date    ^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$
url     ^(http|https)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$
phone   ^([\+][0-9]{1,3}([ \.\-])?)?([\(]{1}[0-9]{3}[\)])?([0-9A-Z \.\-]{1,32})((x|ext|extension)?[0-9]{1,4}?)$

Upvotes: 2

Related Questions