【问题标题】:Form validation error. Form is allowing empty fields?表单验证错误。表单允许空字段?
【发布时间】:2013-09-11 10:37:41
【问题描述】:

我有一个简单的联系表格,其中包含姓名、电子邮件、号码和消息。 我已经使用 javascript 来验证它并提供反馈。所有其他功能都可以正常工作,如果输入框包含无效字符或值,它们会变成红色。但是,当我对所有框执行存在检查时,即使只有一个输入中有值,表单也会提交。

这是我的 jS...

function submit_it() {


    var name = document.getElementById("username");
    var email = document.getElementById("email");
    var num = document.getElementById("racenum");
    var messagecontent = document.getElementById("messagecontent");

    var inputs = []; 
    inputs[0] = name; 
    inputs[1] = email;
    inputs[2] = num;
    inputs[3] = messagecontent;

    for(i = 0; i < inputs.length; i++)  // Loop through input elements.
    {
        // Perform presence check.
        if(inputs[i].value=="" || messagecontent.value == 'null') //If check fails
        {
            alert("There are errors in your message form."); // Error
            name.focus(); // Return cursor to first input element.
            break; 
            return;
        }
        else  // If Presence check passes
        {
         $.post("sndmsg.php", { com: "" , pg: ""});
            alert("Your message has been sent."); 
            for(i = 0; i < inputs.length; i++) 
            {
                inputs[i].value = '';
                inputs[i].style.backgroundColor = '#fff';
            }
            break; 
            console.log(logit);
            return;

        }
    }

} 

我假设这是循环或 If 语句的问题,但我不知道为什么它没有发现错误! 任何帮助将不胜感激!

【问题讨论】:

  • 在您的 if(inputs[i].value=="" || messagecontent.value == 'null') 条件下,您可以尝试评论一下 break;声明和检查

标签: javascript arrays forms validation loops


【解决方案1】:

使用这个:

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, '');
  };
}

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

并在您的代码中执行以下操作:

var val = inputs[i].value;

if(val.trim() == "" || messagecontent.value == 'null'){// stuff}

【讨论】:

    【解决方案2】:

    你的循环有缺陷。您实际上是在尝试为每个正确填写的字段发布一次表单。此外,您将永远不会到达 return 语句,因为 break 语句将在此时退出 for 循环。

    您应该在 for 循环完成后 移动 POST 调用,并确保仅在正确填写所有字段时才调用它。像这样的结构(伪代码):

    for...
    {
        if field check fails
        {
            alert, highlight whetever
            return;     // return from whole function
        }
    }
    
    // we come here only if all fields checked ok
    post data
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多