我有一些HTML 5验证工作正常但我现在需要添加一些自定义验证来检查2个输入元素是否具有相同的值。但到目前为止它只是被忽略了。这是我的代码,其中的更改无效:
<script type="text/javascript">
$(document).ready(function () {
//set up buttons
$(function () {
$("input:submit").button();
});
});
</script>
<!--IE doesn't support setCustomValidity-->
<![if !IE]>
<script type="text/javascript">
//http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#the-constraint-validation-api
$(document).ready(function () {
//set up buttons
$(function () {
$("input:submit").button();
});
//added to compare Name and Email Address
var name = $("#Name").val();
var emailAddress = $("#EmailAddress").val();
if ((name == emailAddress) && (name != "")) {
$("#Name").setCustomValidity("Name must not be equal to Email Address");
return false;
}
var elementsInput = document.getElementsByTagName("input");
var elementsTextArea = document.getElementsByTagName("textarea");
for (var i = 0; i < elementsInput.length; i++) {
elementsInput[i].oninvalid = function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
switch (e.target.name) {
case "Name":
e.target.setCustomValidity("@Html.Raw(Resources.Validation.FullNameRequired)");
break;
case "EmailAddress":
//e.preventDefault();
//later you decide you want to submit
//$(this).unbind('submit').submit();
if (e.target.validity.valueMissing) {
e.target.setCustomValidity("@Html.Raw(Resources.Validation.EmailAddressRequired)");
}
else if (e.target.validity.patternMismatch) {
e.target.setCustomValidity("@Html.Raw(Resources.Validation.EmailAddressInvalid)");
}
break;
case "PhoneNumber":
//e.preventDefault();
if (e.target.validity.valueMissing) {
e.target.setCustomValidity("@Html.Raw(Resources.Validation.PhoneNumberRequired)");
}
else if (e.target.validity.patternMismatch) {
e.target.setCustomValidity("@Html.Raw(Resources.Validation.PhoneNumberInvalid)");
}
break;
}
}
};
elementsInput[i].oninput = function (e) {
e.target.setCustomValidity("");
};
}
for (var j = 0; j < elementsTextArea.length; j++) {
elementsTextArea[j].oninvalid = function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
switch (e.target.name) {
case "Details":
e.target.setCustomValidity("@Html.Raw(Resources.Validation.DetailsRequired)");
break;
}
}
};
elementsTextArea[j].oninput = function (e) {
e.target.setCustomValidity("");
};
}
});
</script>
<![endif]>