简体   繁体   English

jQuery基本表单验证问题

[英]jQuery basic form validation issue

After following an online video course, I'm having issues with a basic form validation for a simple contact form. 在关注在线视频课程后,我遇到了简单联系表格的基本表格验证问题。

$("form").submit(function (e) {

    e.preventDefault();

    var error = "";

    if ($("#subject").val() == ""); {

    error += "<p>The subject area is required</p>";

    }

    $("#error").html(error);    

});

When I hit submit, the error message "The subject area is required", displays in a div with an id of "error" which is great but it happens irrespective of whether there is text in the subject box of my form or not which is where the issue lies. 当我点击提交时,错误消息“主题区域是必需的”,显示在ID为“错误”的div中,这很好但是无论我的表单的主题框中是否有文本,它都会发生问题出在哪里。

I've spent a while looking but am not having much luck. 我花了一段时间看,但没有太多运气。 I understand there is a jQuery plugin that may be better option for form validating, however, I'm still a newbie and keen to get this to work. 我知道有一个jQuery插件可能是表单验证的更好选择,但是,我仍然是一个新手并且热衷于让它工作。

Any help would be greatly appreciated! 任何帮助将不胜感激!

Check JQuery custom validation code 检查JQuery自定义验证代码

 $(function() { $("#myForm").submit(function(e) { e.preventDefault(); var fname = $('#fname').val(); if(fname.length >= 0) { $("#error").html('<font color="red">First Name is required</font>'); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <form action="" method="POST" id="myForm"> first name <input type="text" name="fname" id="fname" > <span id="error"> </span> <input type="submit" nmae="submit" value="submit"> </form> 

Try This JQuery validation code 试试这个JQuery验证码

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script> $(function() { $("#error").hide(); $("#myForm").submit(function(e) { e.preventDefault(); var fname = $('#fname').val(); if(fname.length == 0) { $("#error").show(); } else { $("#error").hide(); } }); }); </script> 
  <form action="" method="POST" id="myForm"> first name <input type="text" name="fname" id="fname" > <div id="error">First Name is required</div> <input type="submit" name="submit" value="submit"> </form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM