使用正则表达式的jQuery Validation插件自定义方法 [英] jQuery Validation plugin custom method using regex

查看:119
本文介绍了使用正则表达式的jQuery Validation插件自定义方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为jQuery Validator创建一个新方法,并且不知道从哪里开始。

I need to make a new method for jQuery Validator and don't know where to start.

我想检查输入的电子邮件是否包含:'@ specificdomain.com'。

I would like it check that the email entered includes: '@specificdomain.com'.

但它也是输入的最后一部分。例如@ specificdomain.comChris不会这样做。

But that it is also the very last part of the input. For example @specificdomain.comChris would not do.

<script type="text/javascript">
    jQuery.validator.addMethod("mustinclude", function(value, element) {
        return this.optional(element) || value == ?
        }, "must include @specificdomain.com at the end of the text input");

    $(document).ready(function(){ .....

到目前为止,我只遇到了值== value.match(),因此这就是我遇到的问题。

So far I've only come across value == value.match(), hence this is where I've got stuck.

干杯克里斯

        jQuery.validator.addMethod('matchDomain', function(value, element) {
        var s=value;
        var split = s.split('@');
        var regex = /^([a-zA-Z0-9_.+-])+$/;
        var s2="@allcoles.com";
        var optionalValue = this.optional(element);

        if (optionalValue) {
            return optionalValue;
            }
        if(regex.test(split[0]) && s2.equals(split[1]))
            {
            return true;
            }
        else
            {
            return false;
            }
        }, 'Please specify a @allcoles.com email');     


推荐答案

以下w orked for me:

The following worked for me:

jQuery.validator.addMethod('matchDomain', function(value, element) {
        var s=value;
        var split = s.split('@');
        var regex = /^([a-zA-Z0-9_.+-])+$/;
        **var s2="allcoles.com";**                  //The split array is the domain excluding the @
        **var optionalValue = this.optional(element);** //This is how other methods in alternativeMethods.js Validator handle this.

        **//Debugging - This is useful to see visually what is happening
        //alert(split[0]);  // Shows the inputted username i.e chris or smokey
        //alert(split[1]);  // Shows the inputted domain
        //alert(regex.test(split[0]));  //Shows unfilled inputs problem or bad characters, true if good, false if bad
        //alert(s2 == split[1]);**  // Shows if the inputted domain matches variable s2, if it does we get a true

        if (optionalValue) {
            return optionalValue;
            }
        **if(regex.test(split[0]) && (s2 == split[1]))**  // has to be == not equals
            {
            return true;
            }
        else
            {
            return false;
            }
        }, 'Please specify a @allcoles.com email');

这篇关于使用正则表达式的jQuery Validation插件自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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