简体   繁体   English

使用JQuery Validator插件集成自定义功能和规则

[英]Integrating custom function and rule using JQuery validator plugin

I have a form with an email field. 我有一个带有电子邮件字段的表格。
As part of the validation I would like to exclude certain domains ( eg gmail,yahoo etc ) 作为验证的一部分,我想排除某些域(例如gmail,yahoo等)

I have found the following function which should search for substrings which I believe is a good choice to search my email strings in: jquery/javascript check string for multiple substrings : 我发现以下功能应该搜索子字符串,我认为这是在以下位置搜索我的电子邮件字符串的不错选择: jquery / javascript检查多个子字符串的字符串

function isSubStringPresent(str){
    for(var i = 1; i < arguments.length; i++){
        if(str.indexOf(arguments[i]) > -1){
            return true;
        }
    }    
    return false;
}    

isSubStringPresent('myemail', 'gmail', 'yahoo', ...)

I am confused on how to integrate this function with the jquery validator plugin. 我对如何将此功能与jquery验证程序插件集成感到困惑。

Please see below: 请看下面:

I have the following following below my form: 我的表格下面有以下内容:

$(document).ready(function(){ 
    $.validator.addMethod(
                    "wrong_domain",
                    THE isSubStringPresent FUNCTION SHOULD BE INSERTED HERE SOMEHOW...                    
                    },
                    'Not an acceptable email' );

    $.validator.classRuleSettings.wrong_domain = { wrong_domain: true};    

$('#registration-form').validate({
        rules: {
           FirstName: {
            required: true,
          },

           Email: {
            required: true,
            email: true,
            wrong_domain: true
          },

Can someone show me how to do this? 有人可以告诉我该怎么做吗?

Try using apply to pass in multiple excluded domains to the validation function: 尝试使用Apply将多个排除的域传递给验证功能:

var excludes = ['myemail', 'gmail', 'yahoo'];
$.validator.addMethod(
    "wrong_domain",
    function(value, element) { 
        // take a shallow copy of excludes
        var myArguments = excludes.slice(0);
        // add value to the front of the arguments
        myArguments.unshift(value);
        // use myArguments as the arguments array for isSubStringPresent
        return !isSubStringPresent.apply(this, myArguments);
    },
    'Not an acceptable email' );

Here's an example Fiddle . 这是一个小提琴的例子。 This will validate the input after every keypress event. 这将在每次keypress事件之后验证输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM