jQuery验证-输入两个确切的长度 [英] jquery validate - input with two exact lengths

查看:126
本文介绍了jQuery验证-输入两个确切的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证可以包含8个或11个字符的输入.我不相信有一种现有的方法.

I am trying to validate an input which can have either 8 or 11 characters. I don't believe there's a method existing.

我有八种不同的输入形式可以进行验证.我扩展validate()方法,并为输入分配规则和showErrors.当用户单击保存"时,我将调用$ form.valid()进行验证并显示错误消息.一种方法是将新规则添加到jquery验证文件.我想知道是否还有其他方法可以在触发该事件的文件中进行验证.

I have eight different inputs to validate in a form. I extend the validate() method and assign rules and showErrors for the inputs. When the user clicks Save, I call $form.valid() to validate and display error messages. One way is to add a new rule to the jquery validate file. I wonder if there's another way like validating in the file where I trigger this event.

谢谢.

推荐答案

如果要在submit上验证表单,例如可以这样做.

If you want to validate the form on submit you can do it like this for example.

HTML:

<form>
  <input class="to-validate" name="someInput" type="text" />
</form>

JS:

$("form").submit(function(e) {
    var inputValueLength = $("input.to-validate", $(this)).val().length;

    if( inputValueLength != 8 && inputValueLength != 11 ) {
        e.preventDefault();

        // do somthing here, like display an error message

        return false;
    }
});


您甚至还可以直接在更改时验证输入:


You can even validate an input directly on change too:

$("input.to-validate").change(function() {
    var inputValueLength = $(this).val().length;

    if( inputValueLength != 8 && inputValueLength != 11 ) {
        // do somthing here, like display an error message
    }
});

这篇关于jQuery验证-输入两个确切的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆