Simple Ajax validation for WordPress Registration Form

Just install and WordPress registration form will use ajax validation (no reload).

You can customize it to add javascript effects/events.

https://github.com/diego-betto/papion-ajax-regvalidation

Registration Hook (PHP)

Diego Betto
   Description: WordPress Ajax Registration Form Validation
   Text Domain: papion-plugins
   License: GPLv3
  */

   defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

function papion_validate( $errors, $sanitized_user_login, $user_email ) {
    if(isset($_POST['validation_test'])){

        if($errors && count($errors->errors) > 0) {
            $errors->add( 'validation_status', -1);
            wp_send_json($errors);
        } else {
            $errors->add( 'validation_status', 1);
            wp_send_json($errors);
        }       
    } 
    
    return $errors;
}

add_filter( 'registration_errors', 'papion_validate', 10, 3 );

add_action( 'login_enqueue_scripts', function(){
    wp_enqueue_script('jquery-core');
    wp_register_script( 'reg-ajax', plugins_url( '/papion-ajax-regvalidation.js', __FILE__ ), array ('jquery'));
    wp_enqueue_script('reg-ajax');
} );

and Ajax Validation (javascript)

jQuery(document).ready(function(){
    jQuery('#registerform').on('submit',function(e){
        var $form = jQuery('#registerform');
        e.preventDefault();
        jQuery('#login_error').remove();
        if(!$form.hasClass('validated')){
            $form.append('');
            var datastring = $form.serialize();
            jQuery.ajax({
                type: "POST",
                url: $form.attr('action'),
                data: datastring,
                dataType: "json",
                success: function(data) {
                    if(data.errors && data.errors.validation_status){
                        if(data.errors.validation_status[0] === 1){
                            $form.addClass('validated');
                            $form.off().submit();
                        } else {
                            $form.before('
'); var htmlErrors = ''; for(var k in data.errors) { if(k !== 'validation_status') { htmlErrors += data.errors[k] + '
'; } } jQuery('#login_error').html(htmlErrors); } } }, error: function() { alert('error handing here'); } }); $form.find('.validation_test').remove(); } }); });

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.