0

嗯..如果用户没有填写姓名、电子邮件或消息,我想向用户展示他们需要填写的内容。例如,他们填写了姓名,但没有填写电子邮件和消息,因此会出现错误显示他们应该填写他们的电子邮件和消息。我的代码在这里显示所有错误,即使他们填写了他们的名字。

function validate() {
    var myName = document.getElementById("inputName");
    var myEmail = document.getElementById("inputEmail");
    var filter = /^[_a-z0-9]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i;
    var myMessage = document.getElementById("inputMessage");
    var isValid = true;

    if(myName.value == "") {
        var myNameError = document.getElementById("inputNameError");
        myNameError.innerHTML = "Please provide your name.";
        isValid = false;
    }

    if (!filter.test(myEmail.value)) {
        var myEmailError = document.getElementById("inputEmailError");
        myEmailError.innerHTML="Please provide your email.";
        isValid = false;
    }       

    if(myMessage.value == "") {
        var myMessageError = document.getElementById("inputMessageError");
        myMessageError.innerHTML = "Please provide your message.";
        isValid = false;
    }

    return isValid;
}
4

2 回答 2

1

You could give jQuery validation a try: http://jqueryvalidation.org/documentation/

It will relieve you of many validation headaches...

于 2013-08-11T08:53:21.117 回答
0

如果我对你的问题的理解是正确的。以下是您的方案:

  1. 第一次不为任何字段赋值时,会显示所有错误。
  2. 其次,您输入名称字段并期望名称错误确实消失,但仍然显示。

原因是因为每个输入字段有 1 个错误划分(总共 3 个),并且当输入存在时它们不会隐藏。您可以修改您的代码如下:

function validate() {
    var myName = document.getElementById("inputName");
    var myEmail = document.getElementById("inputEmail");
    var filter = /^[_a-z0-9]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i;
    var myMessage = document.getElementById("inputMessage");
    var isValid = true;

    var myNameError = document.getElementById("inputNameError");
    var myEmailError = document.getElementById("inputEmailError");
    var myMessageError = document.getElementById("inputMessageError");

    //Initially hide all previous error messages.
    myNameError.className="hidden";
    myEmailError.className="hidden";
    myMessageError.className="hidden";

    if(myName.value == "") {
        myNameError.className="visible";//make error message div visible only on error.
        myNameError.innerHTML = "Please provide your name.";
        isValid = false;
    }

    if (!filter.test(myEmail.value)) {
        myEmailError.className="visible";//make error message div visible only on error.
        myEmailError.innerHTML="Please provide your email.";
        isValid = false;
    }       

    if(myMessage.value == "") {
        myMessageError.className="visible";//make error message div visible only on error.
        myMessageError.innerHTML = "Please provide your message.";
        isValid = false;
    }

    return isValid;
}

CSS

.hidden {display: none;}
.visible {display: block;}

编辑根据评论添加小提琴链接。

于 2013-08-11T08:59:18.557 回答