我有一个带有jquery验证的表单。我有一些自定义规则,但它们都签出并在其他表单上正常工作。事实上,除了一个特定的情况外,它在这种形式上运行得很好。我们有一个URL的文本输入。我们写了一个正则表达式来禁止脚本标记。它工作正常。
如果您填写错误表单并提交,则会收到错误消息。正如所料。但是此URL字段...如果您在失败之前输入了有效的URL,然后将其更改为脚本标记并单击“保存”,则会立即显示错误消息,但无论如何都会提交表单。如果您首先远离该字段,则会看到错误消息。但点击“保存”仍会保存表单。
我尝试使用页面加载功能来禁用表单操作,并使用检查表单是否有效来替换操作。如果将表单留空并单击“保存”,则会出现错误。如果你填写它,你什么也得不到。单击“保存”不执行任何操作。
这是我的表单标签。这些领域并不重要。这里的问题是表单未通过验证但仍然保存:
<form id="frmCreateNewAd" action="/some/path" method="post" enctype="multipart/form-data">
<input class="btnSave" type="submit" value="Save" />
</form>
这是我尝试更改提交操作以禁用默认操作,直到表单通过验证时单击它:
//bind custom form action
$('#frmCreateNewAd').bind("submit", function(e){
//disable default action
e.preventDefault();
//remove previous validation data
$('#frmCreateNewAd').removeData("previousValue");
//check if form is valid
if ($('#frmCreateNewAd').valid()) {
//if form is valid, unbind the submit action and submit the form
$('#frmCreateNewAd').unbind('submit').submit();
}
});
我认为可能问题是尝试在绑定中禁用绑定...但我也尝试使用完全相同的结果
//bind custom form action
$('#frmCreateNewAd').bind("submit", function(e){
//disable default action
e.preventDefault();
//remove previous validation data
$('#frmCreateNewAd').removeData("previousValue");
//validate form
$('#frmCreateNewAd').valid();
});
//When user submits form
$('#frmCreateNewAd').submit(function (e) {
//remove previous validation data
$("#frmCreateNewAd").removeData("previousValue");
//check if form is valid
if($('#frmCreateNewAd').valid()) {
//if valid, unbind custom submit and submit the default action
$(this).unbind('submit').submit();
}
else {
//if invalid, ensure default is still prevented
e.preventDefault();
}
});
我觉得我可能是双重约束提交动作?还有其他人必须克服这个问题吗?
更新:
验证码:
来自全球档案:
if ($.validator) {
$.validator.messages.required = 'Required field';
$.validator.addMethod("zipcode", function(postalcode, element) { return this.optional(element) || postalcode.match(/(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXYabceghjklmnpstvxy]{1}\d{1}[A-Za-z]{1} ?\d{1}[A-Za-z]{1}\d{1})$/); }, 'A valid Zip code is required');
//$.validator.addMethod("urlcustom", function isUrl(str){ var regex = new RegExp("^((http|https|ftp)\://){0,1}([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$"); return regex.test(str); }, 'A valid URL is required');
$.validator.addMethod("alphanumspaces", function alphanumspaces(value, element) { return this.optional(element) || value.match(/^[A-Za-z0-9_\-]+(\s[A-Za-z0-9_\-]+)*$/); }, 'Only letters, numbers, underscores (_), hyphens (-), and single spaces are allowed.');
$.validator.addMethod("alphanumspchars", function alphanumspchars(value, element) {return this.optional(element) || value.match(/^[A-Za-z0-9_\-,\.\#\/\'\"\?]+(\s[A-Za-z0-9_\-,\.\#\/\'\"\?]+)*$/); }, 'Only letters, numbers, single spaces, and simple punctuation (\'\"-,_.#/?) are allowed.' );
$.validator.addMethod("alphaspaces", function alphaspaces(value, element) {return this.optional(element) || value.match(/^[A-Za-z]+(\s[A-Za-z]+)*$/); }, 'Only letters and single spaces are allowed.');
$.validator.addMethod("alphaspspaces", function alphaspspaces(value, element) {return this.optional(element) || value.match(/^[A-Za-z\-\.\(\)]+(\s[A-Za-z0\-\.\(\)]+)*$/); }, 'Only letters, hyphens (-), periods (.), and single spaces allowed');
$.validator.addMethod("numeric", function numeric(value, element) {return this.optional(element) || value.match(/^[0-9]+$/); }, 'Only numbers with no spaces are allowed.'); $.validator.addMethod("statecode", function statecode(value, element) {return this.optional(element) || value.match(/^(A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY]|alabama|alaska|arizona|arkansas|california|colorado|connecticut|delaware|florida|georgia|hawaii|idaho|illinois|indiana|iowa|kansas|kentucky|louisiana|maine|maryland|massachusetts|michigan|minnesota|mississippi|missouri|montana|nebraska|nevada|new\shampshire|new\sjersey|new\smexico|new\syork|north\scarolina|north\sdakota|ohio|oklahoma|oregon|pennsylvania|rhode\sisland|south\scarolina|south\sdakota|tennessee|texas|utah|vermont|virginia|washington|wyoming|d.c.)$/i); }, 'A valid state or two-letter state abbreviation is required.');
$.validator.addMethod("isDollars", function isDollars(value, element) {return this.optional(element) || value.match(/[0-9]+(\.[0-9]{2})?$/); }, 'Must be a valid dollar amount, with or without decimal.');
$.validator.addMethod("keywords", function keywords(value, element) {return this.optional(element) || value.match(/^[A-Za-z0-9]+(,?\s[A-Za-z0-9]+)*$/); }, 'Keywords may only contain letters, numbers, and single spaces. Keywords must be separated by a comma and single space (, )');
$.validator.addMethod("notzero", function notzero(value, element) {return this.optional(element) || value.match(/(^[1-9]+[0-9]*$)|(^0+[1-9]$)/); }, 'Please enter a value greater than zero');
$.validator.addMethod("urlOpt", function urlOpt(value, element) {return this.optional(element) || value.match(/^(((http|https|ftp)\:\/\/){0,1}([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(\/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*)*$/); }, 'Please enter a properly formatted URL');
$.validator.addMethod("noQuoteWrap", function noQuotes(value, element) {return this.optional(element) || value.match(/^[^\'\"].*[^\'\"]$/); }, 'Please remove leading or trailing quotes');
$.validator.addMethod("phoneNum", function phoneNum(value, element) {return this.optional(element) || value.match(/^(1-|1\.|1)?(\([0-9]{3}\)|[0-9]{3})[\.\-]?[0-9]{3}[\.\-]?[0-9]{4}$/); }, 'Please enter a valid phone number, with or without hyphens (-), periods (.), or parenthesis ().');
$.validator.addMethod("spaceStrip", function spaceStrip(value, element) { return this.optional(element) || value.match(/^[.]*$/); }, 'Removing leading and trailing whitespace');
$.validator.addMethod("noScript", function noScript(value, element) { return this.optional(element) || value.match(/^((?!<script).)*$/); }, 'Script tags are not allowed');
// Create and hide error message DOM elements
var errorWrap = document.createElement('div');
$(errorWrap).addClass('errorWrap hideError');
var errorTop = document.createElement('div');
$(errorTop).addClass('errorTop');
var topSpan = document.createElement('span');
var errorContent = document.createElement('div');
$(errorContent).addClass('errorContent');
var errorBottom = document.createElement('div');
$(errorBottom).addClass('errorBottom');
var bottomSpan = document.createElement('span');
$("dl > dd").append(errorWrap);
$("div.errorWrap").append(errorTop)
.append(errorContent)
.append(errorBottom);
$("div.errorTop").append(topSpan);
$("div.errorBottom").append(bottomSpan);
//Set custom placement, highlighting, and unhighlighting
$.validator.setDefaults({
errorPlacement: function(error, element) {
if ($(element).attr("name") == "remnantList") {
$(element).parent().nextAll('.errorWrap').children('.errorContent').append(error);
}
else {
$(element).nextAll('.errorWrap').children('.errorContent').append(error);
}
},
highlight: function(element) {
if ($(element).attr("name") == "remnantList") {
$(element).parent().nextAll('.errorWrap').removeClass('hideError');
}
else {
$(element).nextAll('.errorWrap').removeClass('hideError');
}
},
unhighlight: function(element) {
if ($(element).attr("name") == "remnantList") {
$(element).parent().nextAll('.errorWrap').addClass('hideError');
}
else {
$(element).nextAll('.errorWrap').addClass('hideError');
}
},
onkeyup: false
});
从特定于页面的js文件:
$('form').validate({
errorElement: 'span',
onkeyup: true,
onfocusout: true,
rules: {
'adName': { required: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } }, maxlength:200 },
'adText': { alphanumspchars: true, maxlength:1000, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'thirdPartyImpressionTrackingUrl': { noQuoteWrap: true, maxlength:1000, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'thirdPartyClickTrackingUrl': { noScript: true, noQuoteWrap: true, maxlength:1000, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.destinationUrlView': { required: { depends: destinationUrlRequired }, noQuoteWrap: { depends: isBannerAndFirstFieldIsUrl }, /*number: { depends: isBannerAndIsClickToCall },*/ minlength: function() { return isBannerAndIsClickToCall() ? 10 : false; }, maxlength:1000, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.destinationFile': { required: { depends: isBannerAndDestinationFile }, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[0].multipartFile': { required: { depends: requiredFileUpload }, accept:'jpg|gif|png', spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[1].multipartFile': { required: { depends: requiredFileUpload }, accept:'jpg|gif|png', spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[2].multipartFile': { required: { depends: requiredFileUpload }, accept:'jpg|gif|png', spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[3].multipartFile': { required: { depends: requiredFileUpload }, accept:'jpg|gif|png', spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[4].multipartFile': { required: { depends: requiredFileUpload }, accept:'jpg|gif|png', spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[5].multipartFile': { required: { depends: requiredFileUpload }, accept:'jpg|gif|png', spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[6].multipartFile': { required: { depends: requiredFileUpload }, accept:'jpg|gif|png', spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'videoAdCommand.interactions[0].destinationUrl': { required: { depends: isVideoAndVisible }, maxlength:1000, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'videoAdCommand.interactions[1].destinationUrl': { required: { depends: isVideoAndVisible }, maxlength:1000, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'videoAdCommand.interactions[2].destinationUrl': { required: { depends: isVideoAndVisible }, maxlength:1000, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'videoAdCommand.interactions[3].destinationUrl': { required: { depends: isVideoAndVisible }, maxlength:1000, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'videoAdCommand.interactions[4].destinationUrl': { required: { depends: isVideoAndVisible }, maxlength:1000, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[0].destinationUrl': { maxlength:1000, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[1].destinationUrl': { maxlength:1000, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[2].destinationUrl': { maxlength:1000, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[3].destinationUrl': { maxlength:1000, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[4].destinationUrl': { maxlength:1000, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[0].thirdpartyImpressionUrl': { maxlength:1000, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[1].thirdpartyImpressionUrl': { maxlength:1000, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[2].thirdpartyImpressionUrl': { maxlength:1000, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[3].thirdpartyImpressionUrl': { maxlength:1000, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[4].thirdpartyImpressionUrl': { maxlength:1000, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[0].thirdpartyClickUrl': { maxlength:1000, noScript: true, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[1].thirdpartyClickUrl': { maxlength:1000, noScript: true, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[2].thirdpartyClickUrl': { maxlength:1000, noScript: true, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[3].thirdpartyClickUrl': { maxlength:1000, noScript: true, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'bannerAdCommand.bannerFiles[4].thirdpartyClickUrl': { maxlength:1000, noScript: true, noQuoteWrap: true, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'videoAdCommand.videoMultipartFile': { required: { depends: isVideoAndNoneExists }, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } },
'videoAdCommand.duration': { required: { depends: isVideo }, spaceStrip: { depends: function() { $(this).val($.trim($(this).val())); return false; } } }
},
messages: {
'bannerAdCommand.destinationUrlView': { url: 'Valid URL is required' },
'bannerAdCommand.bannerFiles[0].multipartFile': { required: bannerMissing, accept: bannerType },
'bannerAdCommand.bannerFiles[1].multipartFile': { required: bannerMissing, accept: bannerType },
'bannerAdCommand.bannerFiles[2].multipartFile': { required: bannerMissing, accept: bannerType },
'bannerAdCommand.bannerFiles[3].multipartFile': { required: bannerMissing, accept: bannerType },
'bannerAdCommand.bannerFiles[4].multipartFile': { required: bannerMissing, accept: bannerType },
'bannerAdCommand.bannerFiles[5].multipartFile': { required: bannerMissing, accept: bannerType },
'bannerAdCommand.bannerFiles[6].multipartFile': { required: bannerMissing, accept: bannerType },
'videoAdCommand.videoMultipartFile': { required: videoMissing, accept:'mov|mp4|wmv|avi' }
}
});
答案 0 :(得分:0)
当表单未验证时返回false会怎么样,是否会阻止表单被提交? 。
如果我错了,请纠正我这是你要做的事情: 1)验证用户输入 2)如果所有输入都是正确的提交表格 3)其他显示错误
您的问题是,即使它们是验证错误,它仍会提交表单。
答案 1 :(得分:0)
您是使用jQuery插件进行验证还是使用自定义脚本?我想自己做一些测试。
答案 2 :(得分:0)
这对我有用:
$(document).ready(function () {
$("#frmCreateNewA").validate();
//bind custom form action
$('#frmCreateNewAd').bind("submit", function (e) {
//disable default action
e.preventDefault();
alert($('#frmCreateNewAd').valid());
//remove previous validation data
$('#frmCreateNewAd').removeData("previousValue");
//check if form is valid
if (!$('#frmCreateNewAd').valid()) {
return false
}
});
});
<form id="frmCreateNewAd" action="javascript:alert('success!');">
<input id="txttest" type="text" class="required checkUrl" />
<input class="btnSave" type="submit" value="Save" />
</form>
其中“class”属性指定规则: http://docs.jquery.com/Plugins/Validation/rules
查看docs.jquery.com/Plugins/Validation/valid
答案 3 :(得分:0)
我最后通过添加一个中间层验证器方法来修复此问题,以使用我在jquery验证器上使用的相同正则表达式拒绝来自服务器的值来拒绝脚本标记。这不是我希望解决这个问题的方式,但它确实有效。由于问题似乎是jquery验证器的提交处理程序在某些非常具体的情况下的一些错误,我认为最好还是继续前进。非常感谢所有提供意见的人。