0

你能帮我清理这段代码吗

理想情况下,我想生成一个validateEmail()带参数(email)的函数,然后在表单提交时调用该函数,就像这样

function validateEmail(email){
  // code
}

// Call function on form submission
$('#myform').submit(function() {
   validateEmail($("#txtEmail").val());
})

现在我有这段代码,它对我来说工作得很好,但它使.submit()函数过于混乱,我需要使函数更可重用。

$(document).ready(function() {  
function ValidateEmail(email) {
        var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
        return expr.test(email);
    };

$('#myform').submit(function() {
var abort = false;  
        if (!ValidateEmail($("#txtEmail").val())) {
            $(this).parent().after('<div class="err"> Valid Email Adress Requierd</div>');
            abort = true;
        }
     if (abort) { return false; } else { return true; }
    })//on submit
}); // ready

这是表单的一个工作示例

4

2 回答 2

1
$(document).ready(function() {  
    function ValidateEmail(obj, email) {
        var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
        var testedEmail = expr.test(email);

        var abort = false;  
        if (!testedEmail) {
            $(obj).parent().after('<div class="err"> Valid Email Adress Requierd</div>');
            abort = true;
        }

            if (abort) { return false; } else { return true; }    
    } 

    $('#myform').submit(function() {
        return ValidateEmail(this, $("#txtEmail").val())
    });

}); // ready

这是我的演示

于 2013-11-09T01:11:38.343 回答
0

尝试这个:

var __REGEXINT__ = '__REGEXINT__',

var __REGEXCEP__ = '__REGEXCEP__';

var __REGEXMAIL__ = '__REGEXMAIL__';

var validator = {

    _targetErrors : '#sectionErrors',

    setError: function(msg){

        var message = '<p>{message}</p>'.replace('{message}', msg);

        $(this._targetErrors).append(message)
    },

    __renderInputs : function(__inputs__){


        function __getValueOfTarget(target, delimitator){

            if(!target)
                return false;

            if(typeof target == "string")

                return $(target).val();

            else if(typeof target == "object"){

                var _return_ = [];

                if(!delimitator)
                    delimitator = '';

                for(var id in target)
                    _return_.push(__getValueOfTarget(target[id]));


                return _return_.join(delimitator);
            }

            return false;
        }

        var __return__ = {};
        var __error__ = false;

        for(name in __inputs__){

            var input = __inputs__[name];
            var value = __return__[name] = __getValueOfTarget(input.target, input.delimitator);
            var foundError = false;
            if(!input.validator){

                __return__[name] = value;
                continue;

            } else {

                for(var validatorID in input.validator){

                    if(foundError)
                        continue;

                    switch(input.validator[validatorID]){

                        case 'empty':
                            if(value == ""){
                                __error__ = foundError = true;
                                this.setError(input.validator_error[ validatorID ]);
                                continue;
                            }
                        break;

                        case __REGEXINT__:
                            if(!/^(\d+)$/.test(value)){
                                __error__ = foundError = true; 
                                this.setError(input.validator_error[ validatorID ]);
                                continue;
                            }
                        break;

                        case __REGEXCEP__:
                            if(!/^(\d{5}\-\d{3})$/.test(value)){
                                __error__ = foundError = true; 
                                this.setError(input.validator_error[ validatorID ]);
                                continue;
                            }
                        break;

                        case __REGEXCEP__:
                            if(!/^(\d{5}\-\d{3})$/.test(value)){
                                __error__ = foundError = true; 
                                this.setError(input.validator_error[ validatorID ]);
                                continue;
                            }
                        break;

                        case __REGEXMAIL__:
                            if(!/^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/.test(value)){
                                __error__ = foundError = true; 
                                this.setError(input.validator_error[ validatorID ]);
                                continue;
                            }
                        break;
                    }
                }
            }
        }

        return (__error__) ? false : __return__
    }
}

var __inputs__ = {

    id:{
        target:"#id_terminal",
        validator:["empty", __REGEXINT__ ],
        validator_error:[
            "Por favor insira a ID do terminal.",
            "Por favor insira uma ID valida."
        ]
    },

    name:{
        target:"#name",
        validator:["empty"],
        validator_error:["Por favor insira o nome do estabelecimento."]
    },

    uf:{
        target:"#uf",
        validator:["empty"],
        validator_error:["Por favor insira o estado."]
    },

    mail:{
        target:"#mail",
        validator:["empty", __REGEXMAIL__],
        validator_error:["Por favor insira um e-mail.", "Por favor insira um e-mail valido"]
    },

    cep:{
        target:[".cep", ".cep2"],
        delimitator:'-',
        validator:["empty", __REGEXCEP__ ],
        validator_error:[
            "Por favor insira o cep.",
            "Por favor insira um cep valido."
        ]
    }
}

$('#myform').submit(function() {
    if(!validator.__renderInputs(__inputs__))
        return false;
});
于 2013-11-09T00:40:57.213 回答