验证脚本无法识别动态创建的表单

时间:2014-10-03 15:00:44

标签: jquery html forms validation

在获取表单进行验证方面遇到一些麻烦。我有一个应用程序的一部分,需要填写地址字段。可以选择添加其他地址信息。但是,在显示地址字段并单击提交按钮后,如果添加的字段为空,则不会进行验证。有人可以帮我解决这个问题。我还在下面提供了一些代码。

我想知道是不是因为表格是用javascript添加的。

这是我的javascript:

//validate form

var fields = [
    {
        selector: $('.not-empty'),
        validations: [ isNotEmpty]
    },
    {
        selector: $('.email'),
        validations: [ isNotEmpty, isEmail]
    },
    {
        selector: $('.number'),
        validations: [ isNotEmpty, isNumber]
    },
    {
        selector: $('.number-noreq'),
        validations: [isNumber]
    }
];
$(document.ready(function(){
    $('#job-application-form').on('click', 'button[type=submit]', function(e) {
        e.preventDefault();
        validate();
    });

    $('#add_address').on('click', function(e){
        e.preventDefault();
        $('.address-form').clone().removeClass('address-form').insertAfter('.address-form');
    });
});
function validate(){
    $('.form-control').closest('.form-group').removeClass('has-error');
    var i = 0, k = 0, z = 0, j = fields.length, item, selector, fn, info;
    for(; i < j; i++){
        item = fields[i];
        for(k = 0; k < item.validations.length; k++){
            fn = item.validations[k];
            for( z = 0; z < item.selector.length; z++){
                selector = $(item.selector[z]);
                info = selector.closest('.form-group');
                if(info)
                    info[fn(selector.val()) ? 'removeClass' : 'addClass']('has-error');
            }
        }
    }
}


//validation functions
function isNotEmpty(value){
    return value && $.trim(value).length > 0;
}
function isEmail(value){
    return /^([^@\s\t\n]+\@[\w\d]+\.[\w]{2,3}(\.[\w]{2})?)$/.test(value);
}

function isNumber(value){
    return /^\d+$/.test(value);   
}

这是表格

<span id='address_records' class='app-section'>
                <span class='address-form'>
                    <div class='row'>
                        <div class='col-md-4'>
                            <div class='form-group'>
                                <label>Current Address</label>
                                <input type='text' class='form-control not-empty' name='address[]'>
                            </div>
                        </div>
                    </div>
                    <div class='row'>
                        <div class='col-md-4'>
                            <div class='form-group'>
                                <input type='text' class='form-control' name='address2[]'>
                            </div>
                        </div>
                    </div>
                    <div class='row'>
                        <div class='col-md-2'>
                            <div class='form-group'>
                                <label>City</label>
                                <input type='text' class='form-control not-empty' name='city[]'>
                            </div>
                        </div>
                        <div class='col-md-2 col-md-offset-1'>
                            <div class='form-group'>
                                <label>State</label>
                                <select class='form-control not-empty' name='state[]'>
                                    <? include 'inc/state_list_options.php';?>
                                </select>
                            </div>
                        </div>
                        <div class='col-md-2 col-md-offset-1'>
                            <div class='form-group'>
                                <label>Zip</label>
                                <input type='text' class='form-control not-empty' name='zip[]' maxlength='5'>
                            </div>
                        </div>
                    </div>
                    <div class='row'>
                        <div class='col-md-2'>
                            <div class='form-group'>
                                <label>From</label>
                                <div class='input-group'>
                                    <input type='text' class='form-control half-input not-empty' name='addr_from_month[]'>
                                    <input type='text' class='form-control half-input not-empty' name='addr_from_year[]'>
                                </div>
                            </div>
                        </div>
                        <div class='col-md-2 col-md-offset-1'>
                            <div class='form-group'>
                                <label>To</label>
                                <div class='input-group'>
                                    <input type='text' class='form-control half-input not-empty' name='addr_to_month[]'>
                                    <input type='text' class='form-control half-input not-empty' name='addr_to_year[]'>
                                </div>
                            </div>
                        </div>
                    </div>
                </span>
                <div class='row'>
                    <div class='col-md-12'>
                        <div class='form-group'>
                            <a href="" id="add_address">Add Another Address</a>
                        </div>
                    </div>
                </div>
            </span>

2 个答案:

答案 0 :(得分:1)

我(想)你需要在正在改变的元素范围内使用.on()。我在示例代码中没有看到您的实际提交按钮,所以这只是一个示例

$('#address_records').on('click','button[type=submit]',function(e) {
    e.preventDefault();
    validate();
});

另外,您需要在validate()函数中移动var fields = []声明。目前,您正在定义字段以包含在页面加载时与选择器匹配的DOM元素。此时克隆的元素不存在。它们在运行validate函数时确实存在,因此您希望在此时使用选择器,然后对所有发现的元素运行验证。

答案 1 :(得分:0)

我认为不需要jquery进行表单验证。您使用HTML5和Bootstrap 3的原因。 这是使用HTML5结构的表单验证:

<input type="text" class="" placeholder="" required="required" /> /* Only Text */
<input type="email" class="" placeholder="" required="required" /> /* Only email */
<input type="text" class="" placeholder="Zip Code" required="required" pattern="[0-9]{5}" /> /* Only Zip code US */
<input type="text" class="" placeholder="Telephone" required="required" pattern="[0-9]{11}" /> /* Only Telephone */
type="button"
type="checkbox"
type="color"
type="date"
type="datetime"
type="datetime-local"
type="file"
type="hidden"
type="image"
type="month"
type="number"
type="password"
type="radio"
type="reset"
type="search"
type="submit"
type="tel"
type="time"
type="url"
type="week"
            required="required"
            readonly="readonly"