Javascript 基于原型模式的表单验证

Javascript 基于原型模式的表单验证,javascript,jquery,forms,oop,design-patterns,Javascript,Jquery,Forms,Oop,Design Patterns,我觉得我应该先说我是新来的。我正在使用显示原型模式来验证表单输入,等等。这将是一个验证,它被设置为一种“模板”,将覆盖95%的表单,但某些表单需要添加额外的自定义验证。也就是说,我想做的是创建一个新的表单验证对象,然后初始化它。初始化时,所有求值魔术都会发生,然后将返回“1”=表单有效或“0”=表单无效。我无法理解如何访问“ok”变量以查看它是1还是0。请提前帮助并感谢您 这是表单验证“类”: // Constructor requires the Form's ID of the for y

我觉得我应该先说我是新来的。我正在使用显示原型模式来验证表单输入,等等。这将是一个验证,它被设置为一种“模板”,将覆盖95%的表单,但某些表单需要添加额外的自定义验证。也就是说,我想做的是创建一个新的表单验证对象,然后初始化它。初始化时,所有求值魔术都会发生,然后将返回“1”=表单有效或“0”=表单无效。我无法理解如何访问“ok”变量以查看它是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
}


那么,我遗漏了什么/误解了什么?

您没有将.ok值设置为构造函数中的任何内容,因此我认为您的jquery为空:

var FormValidator = function(formID) {
    this.formID = formID;
    this.ok=1;// set default to 1 (empty jquery select will pass)
    this.currentField;
};
在init中尝试以下方法:

   console.log("Checking inputs:",
       $('input[required], select[required], textarea[required]').length);
在执行.each循环之前,在init函数中

在ini中调用
validateRequiredFields.call(this)
但是您在
$(选择器)中调用它。每个
循环,因此此时
这个
值就是输入的值,然后您将输入的.ok属性设置为0或1。这可以通过以下方法解决:

var init = function() {
    var me=this;
    // Start looking for input, select or textarea that has the 'required' attribute    
    $('input[required], select[required], textarea[required]').each(function() {
        // this is the text input here
        me.currentField = $(this);
        validateRequiredFields.call(me);
        if(!me.ok) {
            return false;
        };

    });
    return true;
},
然后将
this.currentField
设置为输入的id,也许最好将其设置为jQuery对象(参见上面的代码)并使用下面新的this.currentField

validateRequiredFields = function() {
    // Check Dropdown/Text inputs for validity //
    if(this.currentField.selectedIndex == 0 || $.trim(this.currentField.val()) == '') {
    console.log("setting this.ok to 0",this);
        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 {
    console.log("setting this.ok");
        this.ok = 1;
    }
}

编辑我的答案,你发布的代码中有多个错误。这很有效!非常感谢。我想我没有正确地使用
这个
。这就是noob部分。另外,感谢您在构造函数中指定
ok
值时提供的提示。构造函数中的所有状态都应该有一个值吗?因此,将
this.currentField
设置为空字符串更好,还是只创建一个空字符串更好?再次感谢你的帮助。我有更多的验证要建立,但我想让简单的基础工作第一。希望这能让我一路走下去。:)@WizzyBoom`构造函数中的所有状态都应该有值吗?`不,不需要。ok应该设置为1,因为如果没有要检查的元素(没有必填字段),表单将始终是无效的,因为ok将是未定义的。