twitter-bootstrap Bootstrap 3 表单模态,使用 PHP,验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21780684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 20:02:27  来源:igfitidea点击:

Bootstrap 3 form modal, using PHP, validation

phpjqueryvalidationtwitter-bootstrap

提问by Write Down

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

我正在尝试使用 Bootstrap 3 模态函数。我在模态中创建了一个简单的表单。 在此处输入图片说明

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

我的目标是使用 PHP 处理表单,我使用以下脚本进行管理:

$(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).

这工作得很好,我可以将新创建​​的公司添加到数据库等等。输入在服务器端检查,如果不正常,用户会收到一个错误(目前没有完全实现,但这个想法正在起作用)。问题是,我想向用户显示某些字段不正确,而不仅仅是全局错误消息 ( #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).

我发现 jQuery 有一个表单验证选项,但由于某种原因我无法让它工作。最后但并非最不重要的一点是,我想创建一个多语言应用程序。因此,另一个问题是我应该能够更改 jQuery 验证方法产生的错误消息。(我想从我的 process.php 脚本传递这些消息)。

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/

这是我为验证尝试的脚本:http: //jsfiddle.net/v5HQr/1/

Someone could advise me?

有人可以建议我吗?

回答by oceanexplorer

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.

为了使验证正常工作,我必须将引导程序类与 jQuery 相关联。尝试为 jQuery 添加以下默认值,建议您将其放在 JavaScript 文件的顶部。

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

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/

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:

正如我所指出的 - 一些东西,url,电话,电子邮件,日期你可能会发现使用正则表达式更好。以下是我使用过的一些正则表达式:

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}?)$