我已经设法使用JS验证我的文本框,但我知道我需要允许验证码与验证一起工作。
<script>
function validateForm() {
var x = document.forms["reg"]["User"].value;
var letters = "@";
if (x.match(letters))
{
alert("Can't Have Email Address As USERNAME!");
return false;
}
return true;
}
第一表格
<form name="reg" action="DBLogin.php" onsubmit="return validateForm()" method="post">
验证码:
<form action="validate.php" method="post">
Enter Image Text
<input name="captcha" type="text">
<img src="captcha.php" /><br>
<input name="submit" type="submit" value="Register">
</form>
有没有办法让验证码与我的JS验证一起工作?
谢谢
答案 0 :(得分:2)
使用ajax验证验证码。当他提交表格时,发送一个ajax请求来验证验证码。
仅向验证码表单提交一个提交按钮。
<form id ="captcha-form" >
Enter Image Text
<input name="captcha" type="text">
<img src="captcha.php" /><br>
<input name="submit" type="submit" value="Register">
</form>
主要形式:
<form id="main-form" name="reg" action="DBLogin.php" method="post">
<!-- this shoulnt have an submit button -->
现在使用js代码首先验证验证码和验证表单
$("#captcha-form").submit(function(event){
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "validate.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
if(response == "true")
{
validateform();
}
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// handle error
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
现在验证功能
function validateForm() {
var x = document.forms["reg"]["User"].value;
var letters = "@";
if (x.match(letters))
{
alert("Can't Have Email Address As USERNAME!");
}
$("#main-form").submit();
}
正如RiggsFolly指出的那样,不建议这样做。因为这会破坏验证码的目的。