0

我有一个带有 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\.&amp;%\$\-]+)*@)*((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\.\,\?\'\\\+&amp;%\$#\=~_\-]+))*$"); 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\.&amp;%\$\-]+)*@)*((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\.\,\?\'\\\+&amp;%\$#\=~_\-]+))*)*$/); }, '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' }
            }
    });
4

4 回答 4

0

当表单不验证时返回 false 怎么样,这不会阻止表单被提交吗?.

如果我错了,请纠正我这是你想要做的:1)验证用户输入 2)如果所有输入都正确提交表单 3)其他显示错误

您的问题是即使它们是验证错误,它仍然会提交表单。

于 2012-04-04T22:50:49.643 回答
0

您是使用 jQuery 插件进行验证还是使用自定义脚本?我想自己进行一些测试。

于 2012-04-04T23:02:53.500 回答
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>

其中“类”属性指定规则: http ://docs.jquery.com/Plugins/Validation/rules

看看 docs.jquery.com/Plugins/Validation/valid

于 2012-04-05T00:03:57.403 回答
0

我最终通过添加一个中间层验证器方法来解决这个问题,以使用我在 jquery 验证器上使用的相同正则表达式拒绝来自服务器的值来拒绝脚本标签。这不是我希望解决这个问题的方式,但它确实有效。由于在某些极其特殊的情况下,问题似乎是 jquery 验证器的提交处理程序中的一些错误,我认为最好绕过并继续前进。非常感谢所有提供意见的人。

于 2012-04-09T21:06:28.987 回答