【问题标题】:How to get jQuery validate to validate fields that are pre-populated by the browser如何让 jQuery validate 验证浏览器预先填充的字段
【发布时间】:2014-01-06 20:37:00
【问题描述】:

我有一个表单,它从最终用户那里收集一些个人信息并触发一些 JS 验证功能。对于简单的示例,我们只说表单包含名字、姓氏和电子邮件地址。

现在,一旦填写并提交了表单,如果我返回到它,我的浏览器就会像您期望的那样预先填充表单。问题是当我提交时(不更改任何字段或通过它们切换)插件不会返回并验证这些字段(如果它们已被预先填充。

我不确定为什么它不验证预填充的字段。我不知道如何得到它。有没有人有任何想法?我正在运行最新版本的 jQuery 和验证插件 (http://jqueryvalidation.org/)。

示例代码:

$(document).ready(function() {
    var rules = {
        FirstName: 'required',
        LastName: 'required',
        EmailAddress: {
            required: true,
            customEmail: true,
            checkAccountExists: true
        }
    };

    //And field specific (and even validation type specific) error messages
    var messages = {
        FirstName: 'Your first name is required.',
        LastName: 'Your last name is required.',
        EmailAddress: {
            required: 'Your email address is required.',
            customEmail: 'You must enter a valid email address.',
            checkAccountExists: 'We already have an account with that email address. Please login.'
        }
    };

    $('#applicationForm').validate({
        //debug: true,
        rules: rules,
        messages: messages,
        errorElement: 'span'
    });
});

jQuery.validator.addMethod('customEmail', function(value, element) {
    return this.optional(element) || /[A-z0-9._%-+]{1,}@[A-z0-9._%-]{1,}\.[A-z0-9._%-]{1,}/.test(value);
}, 'Invalid email address entered.');


jQuery.validator.addMethod('checkAccountExists', function(value, element) {
    if (this.optional(element)) {
        return true;
    }

    var url = $(element).attr('checkEmailUrl');

    $.ajax({
        type: 'GET',
        data: {EmailAddress: value, check: true},
        dataType: 'json',
        url: url,
        success: function(response) {
            var dataArray = jQuery.parseJSON(response);

            //If it exists then trigger the popup
            if (dataArray.result == 'EXISTS') {
                kclHelpers.showEmailExistsModal(value);
            }
        }
    });

    return true; //If it exists the popup will handle it. We are just using this to trigger it
}, 'An account under the specified email address already exists. Please sign in.');

【问题讨论】:

标签: javascript jquery forms validation


【解决方案1】:

我采用的一个简单解决方案是触发已经绑定到您要验证的元素的模糊事件。您可以检查每个元素的值以确定是否应验证它们,从而防止此操作在用户交互之前触发它们。

$(window).load(function() {
    //pre-highlight fields with values
    $('input[type=text], input[type=email], input[type=url], input[type=password], select').filter(function() {
        return $.trim($(this).val()) != '';
    }).blur();
});

【讨论】:

    猜你喜欢
    • 2021-06-30
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    相关资源
    最近更新 更多