我正在尝试在jQuery中编写一个快速且脏的表单验证脚本
我需要能够从'init'方法范围之外的'settings'对象中访问属性,我试图用另一种方法来控制它,我称之为'验证'我可以'我只是将对象作为参数传递给validate方法,因为我需要稍后调用我的validate方法。这是我的剧本:
(function($) {
var methods = {
init: function(options) {
var settings = $.extend({
bgColor: '#fff',
textType: 'normal',
textColor: '#666',
errorMsgClass: 'errorMsg',
requiredMsgClass: 'requiredMsg',
ex: {
'email': /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/,
'message': /^[0-9a-zA-Z ."']+$/,
'name': /^[0-9a-zA-Z,\r\n ."']+$/,
'phone': /^[0-9 ]+$/,
'url': /^[0-9a-zA-Z,\r\n ."']+$/
}
}, options)
return this.each(function() {
var o = settings;
var obj = $(this);
var items = $(":input", obj);
items.each(function() {
if (this.parentNode.className.substr(0, 8) == 'validate') {
$(this).bind({
focus: function() {
if ($(this).val() == $(this).attr('id')) {
$(this).val('');
}
methods.msgHide($(this), '.errorMsg')
},
blur: function() {
methods.validate($(this))
}
});
}
});
});
return settings;
},
validate: function(el) {
if (el.val() == '') {
methods.is_required ? methods.msgShow(el, '.requiredMsg') : '';
el.val(el.attr('id'))
}
else {
//hide required msg
methods.msgHide(el, '.requiredMsg');
var last = methods.get_length(el);
var reg = methods.getWrapper(el).attr('class').substr(9, last);
if (!el.val().match(methods.init.ex[reg])) {
methods.msgShow(el, '.errorMsg')
}
}
},
get_length: function(el) {
//see if it has the trailing asterix
if (methods.is_required) {
return el.closest('div').attr('class').length - 10;
}
else {
return el.closest('div').attr('class').length - 9;
}
},
is_required: function(el) {
//see if it has the trailing asterix
if (el.closest('div').attr('class').lastIndexOf('*') > -1) {
return true
}
else {
return false
}
},
getWrapper: function(el) {
return el.closest('div');
},
msgShow: function(el, message) {
methods.getWrapper(el).children(message).css({
display: "block"
});
},
msgHide: function(el, message) {
methods.getWrapper(el).children(message).css({
display: "none"
});
},
};
$.fn.validateForm = function(method) {
// Method calling logic
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.validateForm');
}
};
})(jQuery);
答案 0 :(得分:0)
您可以将设置对象传递给任何需要它的函数。
functionThatNeedsSettings(settings);