0

有人能告诉我我的 jQuery 验证有什么问题吗?它没有验证我的表单,而是忽略了导致不检查输入的代码。

形式:

<form class="form" accept-charset="UTF-8" action="URL-to-complete-form" method="POST" onsubmit="return validateForm();">
<input class="form-name" type="text" placeholder="Name"></div>
<input class="form-email" type="text"placeholder="Email"></div>
<input style="background-color: #fc8f12;" type="submit" value="Subscribe">
</div>
</form>

Javascript:

function validateForm()
{
    // Validate Name
    var title = $(".form-name").val();
    if (title=="" ||title=="Name" || title==null) { } else {
        alert("Please enter a name!");
    }

    // Validate Email
    var email = $(".form-email").val();
    if ((/(.+)@(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email=="Email" || email==null) { } else {
        alert("Please enter a valid email");
    }
  return false;
}

感谢大家的时间和帮助。

4

3 回答 3

0

To me it looks like you're not doing anything to prevent the form from being submitted, because you have the "action=" line in the form... you're telling it to, on submit, both run the javascript function and submit the form. You should have the javascript submit the form after it's validated. There are plenty of ways of doing it... probably the easiest is to make the submit button a type button instead of type submit, and then bind the validation and submission to the click of that button.

于 2013-11-10T07:44:40.857 回答
0

由于您正在“干预”提交回发以进行验证,因此请转移您的代码以使其清晰,从表单中删除提交按钮,根据按钮单击进行验证并使用有效数据执行您自己的表单自定义回发:

 <form class="form" accept-charset="UTF-8" method="POST" action="#">
        <input class="form-name" type="text" placeholder="Name"></div>
        <input class="form-email" type="text" placeholder="Email"></div>
        </div>
    </form>
    <button>Subscribe</button>

 $(function () {
            $('button').on('click', function (event) {
                validateForm();
            });

        });

        function validateForm() {
            // Validate Name
            var title = $(".form-name").val();
            if (!title) {
                alert("Please enter a name!");
                return false;
            }

            // Validate Email
            var email = $(".form-email").val();
            if (!email) {
                alert("Please an email address");
                return false;
            }

            if (!/(.+)@(.+){2,}\.(.+){2,}/.test(email)) {
                alert("Please enter a valid email");
                return false;
            }

            $.post('URL-to-complete-form', $("form").serialize(), function (data) {
                console.log('server call complete');
                console.log(data);
            });

        }

这里也是一个工作 jsFiddle:http: //jsfiddle.net/t8vQ2/

于 2013-11-10T08:26:52.413 回答
0

HTML:

<form id="form1" ...

jQuery:

$("#form1").on("submit", function(){
  if($("input[name=firstName]").val() == ""){
    // errors here
    return false;
  }
});
于 2013-11-10T09:49:29.803 回答