在表单提交上调用javascript函数(使用jquery表单验证)

时间:2014-09-29 03:44:42

标签: javascript php jquery forms validation

我有一个使用jQuery Validation插件设置的表单。

见这里:http://jsfiddle.net/9q865xof/

我在添加插件之前从我的表单验证方法中获得了这个(非jquery)javascript函数。

function busregform(form, password) {

// new input for hashed password
var p = document.createElement("input");

// create element
form.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = hex_sha512(password.value);

// clear plaintext password 
password.value = "";

// submit the form
form.submit();
return true;

}

将hex_sha512()函数放在自己的文件中。

这里的想法是通过busregform()从表单发布密码以创建哈希密码,然后发布我的PHP脚本进行处理。

我已经尝试将此添加到我的验证jquery代码中:

submitHandler: function(){
  var pw = $("#pass").val();
  var form = $("#business-reg-form");
  busregform(form,pw);
}

没有运气......不知道现在该做什么。我想我应该使用ajax?

如何在提交插件验证表单时调用busregform()?

1 个答案:

答案 0 :(得分:0)

busregform方法期待form的dom元素引用,因此您需要

$('#business-reg-form').validate({
  rules: {
    address: {
      required: true,
      minlength: 6
    },
    email: {
      required: true,
      email: true,
      minlength: 6
    },
    company: {
      required: true
    },
    pass: {
      required: true,
      minlength: 6
    },
    confirmpw: {
      required: true,
      minlength: 6,
      equalTo: "#pass"
    }
  },
  submitHandler: function() {
    var pw = $("#pass");
    var form = $("#business-reg-form");
    //pass the dom element reference
    busregform(form[0], pw[0]);
    return false;
  }
});

function busregform(form, password) {

  // Create a new element input, this will be our hashed password field. 
  var p = document.createElement("input");

  // Add the new element to our form. 
  form.appendChild(p);
  p.name = "p";
  p.type = "hidden";
  p.value = hex_sha512(password.value);

  // Make sure the plaintext password doesn't get sent. 
  password.value = "";

  // Finally submit the form. 
  form.submit();
  return true;

}

if (!window.hex_sha512) {
  //stub method
  window.hex_sha512 = function(value) {
    return 'hex_sha512-' + value;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<form method="post" name="business_regform" id="business-reg-form" action="">
  <p>
    <input type="text" name="company" id="company" placeholder="company name" required />
  </p>
  <p>
    <input type="text" name="address" id="address" placeholder="address" required />
  </p>
  <p>
    <input type="text" name="email" id="email" placeholder="email" required />
  </p>
  <p>
    <input type="text" name="pass" id="pass" placeholder="password" required />
  </p>
  <p>
    <input type="text" name="confirmpw" id="confirmpw" placeholder="confirm password" required />
  </p>
  <p>
    <input type="submit" class="btn" id="business-reg-submit" value="submit" />
  </p>
</form>
演示:Fiddle - 您可以使用网络标签检查请求以查看散列密码