パターン化は初めてだと言うことから始めるべきだと思います。フォーム入力などを検証するために、公開プロトタイプ パターンを使用しています。これは、フォームの 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
}
それで、私は何が欠けている/誤解していますか?