我觉得我应该首先说我是新的图案。我正在使用显示原型模式来验证表单输入等。这将是一个设置为某种“模板”的验证,它将覆盖我们 95% 的表单,但需要添加某些表单额外的自定义验证。话虽如此,我想要做的是创建一个新的表单验证对象,然后对其进行初始化。在初始化时,所有的求值魔法都会发生,然后将返回一个 '1' = 表单有效或一个 '0' = 表单无效。我无法理解如何访问我的“确定”变量以查看它是 1 还是 0。请提前帮助并感谢您。
这是表单验证“类”:
// Constructor requires the Form's ID of the for you want to validate
// Exmaple: FormValidator('MyContactForm')
var FormValidator = function(formID) {
//state
this.formID = formID; //I was thinking of having this.formID in case there are two forms that need validating on a single page. (e.g., Search box and Contact Form) I don't seem to be using this correctly?
this.ok; //want to access this to see if the form validated or not
this.currentField; //using this to identify what form field is getting evaluated
};
FormValidator.prototype = function() {
//private memebers
var init = function() {
// Start looking for input, select or textarea that has the 'required' attribute
$('input[required], select[required], textarea[required]').each(function() {
//--Set Current Field Under Evaluation--//
this.currentField = $(this).attr('id');
validateRequiredFields.call(this);
if(!this.ok) {
return false;
};
});
},
validateRequiredFields = function() {
// Check Dropdown/Text inputs for validity //
if($(this.currentField).selectedIndex == 0 || $.trim($(this.currentField).val()) == '') {
this.ok = 0;
return false;
}
// Check Radio/Checkbox inputs for validity //
else if(this.currentField.attr('type') == 'radio' || this.currentField.attr('type') == 'checkbox') {
var optChecked = $('input[name="' + this.currentField.attr('name') + '"]:checked')
if($(optChecked).length == 0) {
this.ok = 0;
return false;
}
}
else {
this.ok = 1;
}
}
return {
//public members
init: init
};
}();
创建新对象并初始化它:
var validateForm = new FormValidator('mobileSchedulingForm');
validateForm.init();
console.log(validateForm.ok); //undefined (how come?)
if(validateForm.ok) { //Eval failing cause 'validateForm.ok' is undefined?
// do something now that the form is valid
}
那么,我错过了什么/误解了什么?