使用揭示原型模式进行表单验证

时间:2013-07-18 21:36:10

标签: javascript jquery forms oop design-patterns

我觉得我应该首先说我是新模式。我正在使用显示原型模式来验证表单输入等。这将是一个验证,设置为一种“模板”,将覆盖我们95%的表单,但是需要添加某些表单在路上进行额外的自定义验证。这就是说我想要做的是创建一个新的表单验证对象然后初始化它。初始化时,所有评估魔法都会发生,然后返回'1'=表格有效或'0'=表格无效。我无法理解如何访问我的'ok'变量以查看它是1还是0.请提前帮助并谢谢。


这是表单验证'class':

// 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
}

那么,我错过了什么/误会?

1 个答案:

答案 0 :(得分:1)

你没有将.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);,但是您在$(selector).each循环内调用它,所以此时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;
    }
}