【问题标题】:return true from javascript then form continue to submit从javascript返回true然后表单继续提交
【发布时间】:2019-08-01 12:27:20
【问题描述】:

我有 php 页面和 javascript,该页面是联系我们的表单,并且在提交按钮之前有验证码,当表单提交时它会检查验证码是否验证返回 true,否则警报并再次创建验证码,但是当它返回 true 时它不起作用之后什么都没有发生

<?php
$action=$_REQUEST['action'];
if ($action=="")    /* display the contact form */
    {
    ?>
<form action="" id="demo-form" onsubmit="validateCaptcha()" method="POST" enctype="multipart/form-data" >
    <h3>Quick Contact</h3>
    <h4>Contact us today, and get reply with in 24 hours!</h4>
        <input type="hidden" name="action" value="submit">
      <input placeholder="Your name" name="name" id="name" type="text" tabindex="1" required autofocus><br>

      <input placeholder="Your Email Address" name="email" id="mail" type="email" tabindex="2" required><br>

      <input placeholder="Subject" id="sub" name="subject" type="text" tabindex="3" required><br>

      <input placeholder="Mobile Number" name="number" pattern="^((\+92)|(0092)|(0))-{0,1}\d{3}-{0,1}\d{7}$|^\d{11}$|^\d{4}-\d{7}$" id="contactInformation" type="tel" tabindex="4" oninvalid="this.setCustomValidity('Enter mobile number like: 03001234567')"
      oninput="this.setCustomValidity('')" > <br>
      <textarea placeholder="Type your Message Here...." tabindex="6" name="message" id="msg" tabindex="5" required></textarea><br>
      <div id="captcha">
    </div><input type="text" placeholder="Enter Captcha Code Here" id="cpatchaTextBox"/><br>
      <input name="submit" type="submit" value="Submit" tabindex="7" id="contact-submit" data-submit="...Sending" /><br>
        <button type="reset" name="reset" tabindex="8" id="contact-reset">Clear Form</button>
 </form>
<?php
    } 
else                /* send the submitted data */
    {
    $name=$_REQUEST['name'];
    $email=$_REQUEST['email'];
    $subject=$_REQUEST['subject'];
    $number=$_REQUEST['number'];
    $message=$_REQUEST['message'];
    if (($name=="")||($email=="")||($subject=="")||($number=="")||($message==""))
        {
        echo "All fields are required, please fill <a href=\"\">the form</a> again.";
        }
    else{        
        $from="From: $name<$email>\r\nReturn-path: $email";
        $msg= "Name: ".$name."\nContact Number: ".$number."\n".$message ;
        mail("xyz@gmail.com", $subject, $msg , $from);
        echo '<script type="text/javascript">',
        'alert("EMAIL SENT..!");',
        'setTimeout(function(){',
          ' window.location.href = "thanks.php";',
        ' }, 50);',
        '</script>'
;
        }
    }  
?>

</div>
            </section>

               </div>
    <br/>
            </div>
        </div>
    </div> 


// JavaScript Document
var code;
function createCaptcha() {
  //clear the contents of captcha div first 
  document.getElementById('captcha').innerHTML = "";
  var charsArray =
  "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@!#$%^&*";
  var lengthOtp = 6;
  var captcha = [];
  for (var i = 0; i < lengthOtp; i++) {
    //below code will not allow Repetition of Characters
    var index = Math.floor(Math.random() * charsArray.length + 1); //get the next character from the array
    if (captcha.indexOf(charsArray[index]) == -1)
      captcha.push(charsArray[index]);
    else i--;
  }
  var canv = document.createElement("canvas");
  canv.id = "captcha";
  canv.width = 100;
  canv.height = 50;
  var ctx = canv.getContext("2d");
  ctx.font = "25px Georgia";
  ctx.strokeText(captcha.join(""), 0, 30);
  //storing captcha so that can validate you can save it somewhere else according to your specific requirements
  code = captcha.join("");
  document.getElementById("captcha").appendChild(canv); // adds the canvas to the body element
}
function validateCaptcha() {
  event.preventDefault();

  if (document.getElementById("cpatchaTextBox").value == code) {
    return true;
  }else{
    alert("Invalid Captcha. try Again");
    createCaptcha();
  }
}

如果有人可以为我做这件事,我只想在验证码验证表单提交和发送给此人的电子邮件时。

【问题讨论】:

  • &lt;form action="" id="demo-form" onsubmit="return validateCaptcha()" method="POST" enctype="multipart/form-data" &gt; 您在验证表单时错过了表单 onsubmit 的返回值,您应该返回 true 或 false
  • 如果您在客户端创建和验证验证码,则无需担心验证。因为,所有的攻击者都可以通过“code”变量或window[“code”]访问你的验证码值。

标签: javascript


【解决方案1】:

有多种方法可以解决此问题,其中一种更简单的解决方案是仅在需要时才转换 event.preventDefault()无需退货。

function validateCaptcha() {
  if (document.getElementById("cpatchaTextBox").value != code) {
    event.preventDefault();
    alert("Invalid Captcha. try Again");
    createCaptcha();
  }
}

工作演示验证码OK

function validateCaptcha() {
  const captchaMock = false; // switch true/false to see the behavior
  if (captchaMock) {
    event.preventDefault();
    alert("Invalid Captcha. try Again");
    createCaptcha();
  }
}

function createCaptcha() {
  alert('New captcha');
}
<form action="http://www.google.com" onsubmit="validateCaptcha()">
<button>Submit</button>
</form>

工作演示验证码不正常

function validateCaptcha() {
  const captchaMock = true; // switch true/false to see the behavior
  if (captchaMock) {
    event.preventDefault();
    alert("Invalid Captcha. try Again");
    createCaptcha();
  }
}

function createCaptcha() {
  alert('New captcha');
}
<form action="http://www.google.com" onsubmit="validateCaptcha()">
<button>Submit</button>
</form>

【讨论】:

  • 看看我工作的sn-p,从true切换到false看看提交的行为。
  • 是的,它对我有用,现在你解释得很好,我明白我的问题解决了
【解决方案2】:
 onsubmit="validateCaptcha()"

应该是

 onsubmit="return validateCaptcha()"

防止validateCaptcha 的返回值被丢弃。此外,validateCaptcha 需要返回布尔值 false 以防止表单提交 - 返回一些其他虚假值,例如 undefined 不起作用。

您还可以使用将事件对象传递给验证例程

onsubmit="return validateCaptcha( event)"

它允许使用在事件参数上调用的事件方法取消验证例程中的事件。

但是,在 HTML 中添加事件处理程序很容易出错,并且使用 JavaScript 向表单添加提交事件处理程序

formObject.addEventListener("submit", submitHandler, true);

可能更可取 - 提交处理程序以 event 作为参数调用。

【讨论】:

    猜你喜欢
    • 2021-03-29
    • 1970-01-01
    • 2020-06-28
    • 2020-09-25
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    相关资源
    最近更新 更多