繁体   English   中英

如何在不重定向到另一个页面的情况下使用HTML和jQuery进行表单验证?

[英]How to do form validation using HTML and jQuery without redirecting to another page?

我已经编写了HTML表单和脚本来验证表单。 问题是,每当我提交表单时,都会重定向到一个告诉我“找不到您的文件”的页面。

我必须调用脚本的特定方式吗? 或以任何方式可以强制其运行而不重定向我?

<form id="bioform" action="/action_page.php">
  <label>Biography</label><br>
  <textarea placeholder="Enter bio here" name="bio" rows="10" cols="50"></textarea><br><br>
  <label>Update Biography Picture</label><br><br>
  <input type="file" name="bioimage"><br><br>
  <button type="submit" onclick="function()">Update</button><br>
</form>

<script>
  $(document).ready(function () {
    $('#bioform').validate({
        rules: {
          bio {
            required: true,
            minlength: 5,
          },
        }
        messages: {
          bio {
            required: 'Please enter a biography.',
            minlength: 'Please enter a valid biography.',
          },
        }
        });
  });
</script>

将enctype =“ multipart / form-data”添加到表单标签

    <form id="bioform" action="/action_page.php" enctype="multipart/form-data">
     <label>Biography</label><br>
     <textarea placeholder="Enter bio here" name="bio" rows="10" cols="50">
     </textarea><br><br>
     <label>Update Biography Picture</label><br><br>
     <input type="file" name="bioimage"><br><br>
     <button type="submit" onclick="function()">Update</button><br>
    </form>

指定必要的发送地址时,是否使用正斜杠? 例如:

<form id="bioform" action="/action_page.php">

应替换为:

<form id="bioform" action="action_page.php">

由于您使用的是jQuery,请尝试使用此方法:

e.preventDefault()

e.preventDefault()方法停止发生元素的默认操作。 例如:阻止提交按钮提交表单。 阻止链接跟随URL。

另外,由于要处理文件上载,因此需要在<form>标记内添加method属性,其值为POST以及enctype="multipart/form-data"

转到此小提琴并检查它是否对您有用https : //jsfiddle.net/z0db4vq0/1/

暂无
暂无

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

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