【问题标题】:JQuery form gets submitted even validation is returning false即使验证返回错误,也提交了 JQuery 表单
【发布时间】:2009-08-27 13:01:29
【问题描述】:

我下面提到的代码仍然在名称字段中提交特殊字符的表单。验证有效,但如果我反复提交,它会中断并提交名称中带有特殊字符的表单。

这可能是什么原因?

$("#fee").submit(function(){
   trimmedValue = $.trim($("#name").val());
   $("#name").val(trimmedValue);
   typevalue = $("input:radio[@name='type']:radio:checked").val();
   if(typevalue=="FLAT" && !isFloat($("#amount").val())) {
   alert("Amount should be number with proper decimal formatting");
   $("#amount").val("0.0");
    return false;
}
var noSpecialChars = /[^a-zA-Z0-9]/g;
if (noSpecialChars.test($("#name").val())) {
    alert("Please enter valid fee Name. Do not enter special characters"  );
    return false;
}

if(typevalue=="PERCENTAGE" && !isFloat($("#percentage").val())) {
   alert("percentage should be number with proper decimal formatting");
   $("#percentage").val("0.0");
    return false;
}
if(typevalue=="FLAT" && $("#amount").val()=="0.0") {
    return confirm("Do you really want the amount to be 0.0 ?");
}
if(typevalue=="PERCENTAGE" && $("#percentage").val()=="0.0") {
    return confirm("Do you really want the percentage to be 0.0 ?");
}

});

【问题讨论】:

    标签: jquery validation


    【解决方案1】:

    您可以在哪些浏览器中重现此内容?

    我在 Firefox 3.5.2 上做过,但无法在 IE 6.0 上重现。在探索了更多之后,我注意到在这一行......

    if (noSpecialChars.test($("#name").val())) {
    

    ...对 .test() 的调用返回 true,然后是 false,以交替模式(仅在 Firefox 中)表明 RegExp 存在问题。所以我尝试像这样替换 RegExp 的隐式创建:

        //var noSpecialChars = /[^a-zA-Z0-9]/g;        
        var noSpecialChars = new RegExp("[^a-zA-Z0-9]");
    

    这解决了我的问题。

    【讨论】:

    • 感谢这解决了这个问题。想知道如何在这种情况下进行调试。
    • 没问题 - 在这种情况下,我通过向页面添加一个 textarea 元素并写入 noSpecialChars.test($("#name"). val()) 到该文本区域。我还稍微使用了 Firebug 来打消一些早期假设。
    【解决方案2】:

    似乎解释器在反复按下时永远不会到达return false;,而是将表单提交给为表单指定的href

    如果您的表单标记中有href,请尝试将其删除并在调用 return 之前插入属性。

    【讨论】:

    • 我没有表单的 href 属性。我添加了动作和方法属性。
    猜你喜欢
    • 2021-09-01
    • 1970-01-01
    • 2012-09-26
    • 2015-12-15
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2019-09-11
    • 2010-10-19
    相关资源
    最近更新 更多