javascript - 如何让 jQuery 验证以验证浏览器预填充的字段

标签 javascript jquery forms validation

我有一个表单可以从最终用户那里收集一些个人信息并触发一些 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.');

最佳答案

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

$(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();
});

关于javascript - 如何让 jQuery 验证以验证浏览器预填充的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20958808/

相关文章:

html - 我可以为一个表单元素使用多个标签吗?

PHP 和 MySQL - 基于日期和时间的显示表单

javascript - 关于 jQuery AJAX 的问题

javascript - D3 javascript foreach 和 each 的区别

javascript - jquery条件表单提交

jquery - 即收到相同的ajax响应

javascript - 如果 jQuery 表单有效显示隐藏的 div

javascript - jQuery POST 到 Node.JS 失败

javascript - 使用 jQuery 解析 xml 命名空间。需要帮助!

javascript - 禁用输入以便将它们排除在 POST 之外?