Использовать jquery validate с PHP Captcha Code

0

Я пытаюсь использовать плагин Jquery Validate для проверки кода captcha, который является PHP. У меня есть googled это, но я не могу найти и ответить, чтобы заставить мой код работать.

Я вставил свой код ниже, что имеет значение для вопроса

HTML ниже:

<img src="Captcha/captcha.php" name="captcha_img" id="captcha_img" />
        <br/>
        <input style="width:150px; text-align:center;" type="text" id="answer" name="answer" placeholder="Enter captcha here" />
        <br/>
        <input style="width:150px; background-color:#B9C6F0; font-size:10px; height:15px;"  type="button" onclick="document.getElementById('captcha_img').src='Captcha/captcha.php?img=' + Math.random(); return false" value="Refresh Captcha" />

JS ниже:

<script src="JS/jquery.validate.js"></script>
<script  src="JS/additional-methods.min.js"></script>

    <script>
    $(document).ready(function () {

        $("#SignUp").validate({
            onkeyup: function(element) { $(element).valid(); },
            rules: {
                email: {
                    required: true,
                    email: true
                },
                password: {
                    required: true,
                    password: true
                },
                confirm_password: {
                    equalTo: "#password",
                    required: true
                },
                company: {
                    nls:true,
                    required: true
                },
                telephone: {
                    required: true,
                    phoneUK: true
                },
                email2: {
                    email: true
                },
                website: {
                    url: true
                },
                address1: {
                    nls:true
                },
                    address2: {
                    nls:true
                },
                town: {
                    nls:true    
                },
                postcode: {
                    postcodeUK:true
                },
                country: {
                    selectcountry:true
                },
                terms:{
                    required:true               
                },
                answer:{
                    required: true,
                    remote: "Captcha/process.php"

                }

            },
            messages:{
                email:
                        {
                            required: "Please Enter an Email Address"
                        },
                password:
                        {
                            required: "Please Enter a Password"
                        },
                confirm_password:
                        {
                            required: "Please Confirm Your Password"
                        },
                company:
                        {
                            required: "Please Enter Your Company/Climbing Gym Name"
                        },
                telephone:
                        {
                            required: "Please Enter a Telephone Number"
                        },
                terms:
                        {
                            required: "Please Agree Our Terms and Conditions"
                        },
                answer:{
                            required: "Please Enter The Captcha Code",
                            remote: "Captcha Entered Incorrectly"
                        }

            }
        });

        $.validator.addMethod("password", function (value, element) {
            return this.optional(element) || /^[A-Za-z0-9!@#$%^&*()_]{6,16}$/i.test(value);
        }, "Passwords are 6-16 characters");

        $.validator.addMethod("nls", function(value, element)
        {
        return this.optional(element) || /^[a-zA-Z0-9\s.\-_']+$/i.test(value);
        }, "Please Only Enter Alpha Numeric Characters and Spaces"); 


        jQuery.validator.addMethod('selectcountry', function (value) {
            return (value != 'Nothing');
        }, "Please Select a Country");

        $.validator.addMethod("url", function(value, element)
        {
        return this.optional(element) || /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/i.test(value);
        }, "Please Enter A Valid Website URL");


    });
    </script>

PHP ниже:

process.php

<?php

if(strtolower($_POST['answer']) == $_SESSION['captcha']){
    echo 'true';
    }else{
    echo 'false';
    }

unset($_SESSION['captcha']);


?>

captcha.php

<?php
/* captcha.php file*/

    session_start();

    header("Expires: Tue, 01 Jan 2013 00:00:00 GMT"); 
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
    header("Cache-Control: no-store, no-cache, must-revalidate"); 
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");

    $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';

    for ($i = 0; $i < 5; $i++) 
    {
        $randomString .= $chars[rand(0, strlen($chars)-1)];
    }

    $_SESSION['captcha'] = strtolower( $randomString );


    $im = @imagecreatefrompng("captcha-background-rollcode.png"); 


    imagettftext($im, 30, 0, 10, 38, imagecolorallocate ($im, 0, 0, 0), 'larabiefont.ttf', $randomString);

    header ('Content-type: image/png');
    imagepng($im, NULL, 0);
    imagedestroy($im);

?>
Теги:
jquery-validate
captcha

1 ответ

0
Лучший ответ

Добавить правило

answer: {remote: "check-captcha.php" }
При проверке и создании файла check-captcha.php
 if(strtolower($_REQUEST['answer']) == $_SESSION['captcha']) echo '1';
 else '0';
Пожалуйста, проверьте array $_REQUEST для точного индекса (это может быть иначе, чем answer)
  • 0
    Это не сработало, не уверен, что в какой-то момент мне нужно получить jquery validate для подключения к Captcha.php, где генерируется капча?
  • 0
    ты пробовал выше?
Показать ещё 5 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню