【问题标题】:JQuery Validate Plugin Partially FunctionalJQuery 验证插件部分功能
【发布时间】:2014-07-31 09:07:18
【问题描述】:

我正在使用 jquery 验证插件来验证用户名的输入。

$.validator.addMethod("alphanumeric", function(value, element) {
    return this.optional(element) || /^[a-zA-Z0-9\-]+$/i.test(value);
}, "Your username can only contain letters, numbers and hyphens.<br />Spaces and special characters are not permitted.");         

$('.setUsername-form').validate({
    errorElement: 'label', //default input error message container
    errorClass: 'help-inline', // default input error message class
    focusInvalid: false, // do not focus the last invalid input
    ignore: "",
    rules: {
        chosenUsername: {
            required: true,
            minlength: 4,
            alphanumeric: true                          
        }
    },

堆栈溢出错误“您的用户名只能包含....”。这很好。

stackoverflow 不会出错 - 太棒了!

stack-overflow 错误,没有输出。这是一个可接受的用户名,应该可以使用。

有什么想法吗?我无法发现问题。是正则表达式吗?我正在尝试允许使用字母字符、数字字符和连字符。 A-Z、a-z 和 -。 [a-zA-Z0-9\-]不正确吗?

【问题讨论】:

标签: jquery regex jquery-validate


【解决方案1】:

我怀疑您的问题出在代码的其他地方。

这是使用您在上面发布的代码使用 jquery-validate 实现表单的小提琴:

http://jsfiddle.net/klenwell/ZjWWE/

var errorMessage = "Your username can only contain letters, numbers and hyphens.<br />Spaces and special characters are not permitted.";

$.validator.addMethod("alphanumeric", function (value, element) {
    return this.optional(element) || /^[a-zA-Z0-9\-]+$/i.test(value);
}, errorMessage);

function validateForm() {
    var $form = $('form.setUsername-form');
    $form.validate({
        errorElement: 'label', //default input error message container
        errorClass: 'help-inline', // default input error message class
        focusInvalid: false, // do not focus the last invalid input
        ignore: "",
        rules: {
            chosenUsername: {
                required: true,
                minlength: 4,
                alphanumeric: true
            }
        },
    });

    if ($form.valid()) {
        $('div.form-status').css('color', 'green').text('form is valid');
    } else {
        $('div.form-status').css('color', 'red').text('form is invalid');
    }

    return false;
}

$('button.submit-form').on('click', validateForm);

您可以看到它的行为符合预期(在 Chrome 中测试):

  • 堆栈溢出:无效
  • stackoverflow:有效
  • 堆栈溢出:有效

【讨论】:

  • +1 - 谢谢,我不知道我为什么不这样做!吸取的教训...点燃萤火虫! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-22
相关资源
最近更新 更多