這是一個簡單的驗證模塊。現在,我不明白爲什麼我的函數(validateEmail)無法調用成功。我沒有JS錯誤,但瀏覽器確實與我的形式thorought驗證碼回傳JavaScript jq範圍
<script type="text/javascript">
var Validation;
(function (Validation) {
var FormValidator = (function() {
function FormValidator(formid) {
this.emailPattern = /^[a-zA-Z0-9._-][email protected][a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
this.formID = formid;
}
FormValidator.prototype.Validate = function() {
var errorsSum;
$('#' + this.formID).find('input[type="text"][validate], textarea[validate]').each(function (index, item) {
var validateType = $(item).attr('validate');
switch(validateType) {
case 'text':
case 'password': {
errorsSum += FormValidator.prototype.validateText(item);
break;
}
case 'email': {
errorsSum += FormValidator.prototype.validateEmail(item);
break;
}
}
});
return errorsSum == 0;
};
FormValidator.prototype.validateGeneric = function (element, validationFunc) {
var jqElement = $(element);
alert('tested element = ' + jqElement);
if(validationFunc(jqElement.val())) {
alert('tested element error = ' + jqElement.val());
element.removeClass('error');
return 0;
} else {
element.addClass('error');
}
alert('tested element success = ' + jqElement.val());
return 1;
};
FormValidator.prototype.validateEmail = function (element) {
return FormValidator.prototype.validateGeneric(element, function (elementValue) {
return FormValidator.prototype.emailPattern.test(elementValue);
});
};
FormValidator.prototype.validateText = function (element) {
return FormValidator.prototype.validateGeneric(element, function (elementValue) {
return elementValue != '';
});
};
return FormValidator;
})();
Validation.FormValidator = FormValidator;
})(Validation || (Validation = {}));
</script>
這是我的形式
@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @id = "register-form", @class = "form-horizontal"}))
{
...
@Html.TextBoxFor(m => m.Email, new { @placeholder = @L("Email"), @name = "email", @validate = "email" })
...
}
這是驗證碼
<script type="text/javascript">
$(function() {
$('#register-form').submit(function() {
return (new Validation.FormValidator('register-form').Validate());
});
});
</script>
我不明白js這麼深
的HTML HTML生成代碼本身。這是無關緊要的,沒有幫助。 – jbabey
那麼,你是什麼意思,你不能調用'validateEmail'?你能詳細說明嗎? **編輯**您可以在'.each'調用之前引用FormValidator的當前實例,例如'var self = this;',然後從'.each'中使用'self.validateEmail(item)'而不是'FormValidator.prototype.validateEmail'。可能沒有解決這個問題,但如果你能爲我澄清,我可能會幫助更好。 –
如果(validationFunc(jqElement.val()))不返回結果...並且瀏覽器忽略此調用後的所有代碼 – ZOXEXIVO