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

<?php
/*
   Plugin Name: Papion Ajax RegValidation
   Plugin URI: https://papion.it
   Version: 0.9
   Author: <a href="https://diegobetto.com">Diego Betto</a>
   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('<input name="validation_test" class="validation_test" value="1" type="hidden">');
	        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('<div id="login_error"></div>');
							var htmlErrors = '';
							for(var k in data.errors) {
								if(k !== 'validation_status') {
									htmlErrors += data.errors[k] + '<br>';
								}
							}
							jQuery('#login_error').html(htmlErrors);
	                    }
	                }
	            },
	            error: function() {
	                alert('error handing here');
	            }
	        });
			$form.find('.validation_test').remove();
	    }
	});	
});

Leave a Reply

Your email address will not be published. Required fields are marked *

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