jQuery Validator Plugin – verifica el nombre de usuario / correo electrónico existente en la database mysql

He creado con éxito un formulario que envía y agrega usuarios a una database mysql, y la validation de formularios con el complemento 'jQuery Validator' funciona muy bien para todo excepto para verificar si el nombre de usuario ya existe en la database …

Acabo de pasar aproximadamente 8 horas leyendo e intentando encontrar una manera de definir un nuevo método con el complemento 'jQuery Validator'. Parece que no entiendo cómo revisaría la database para el nombre de usuario o correo electrónico ingresado y devolvería si ya existe o no usando jQuery.

Mi código:

<script src="../assets/js/main.js"></script> <script src="../assets/js/ajax.js"></script> <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script> <!-- FORM VALIDATION --> <script type="text/javascript"> jQuery.validator.addMethod("checkExists", function(value, element) { //No idea what to call here }, "Username already exists." ); //<![CDATA[ $(window).load(function(){ $("form").validate({ rules: { username: {minlength: 3, requinetworking: true, checkExists: true}, email: {email: true, requinetworking: true}, pass1: {minlength: 3, requinetworking: true}, pass2: {minlength: 3, requinetworking: true, equalTo: "#pass1"}, country: {requinetworking: true}, tandc: {requinetworking: true}, }, messages: { username: {requinetworking: "You need to enter a Username."}, email: {requinetworking: "You need to enter an Email Address."}, pass1: {requinetworking: "You need to enter a Password."}, pass2: {requinetworking: "You need to enter your password again.", equalTo: "Your passwords don't match."}, country: {requinetworking: "You need to tell us where you live."}, tandc: {requinetworking: "You need to read and agree to the Terms and Conditions to use CGE."} }, showErrors: function(errorMap, errorList) { $.each(this.successList, function(index, value) { return $(value).popover("hide"); }); return $.each(errorList, function(index, value) { var _popover; console.log(value.message); _popover = $(value.element).popover({ trigger: "manual", placement: "right", content: value.message, template: "<div class=\"popover\"><div class=\"arrow\"></div><div class=\"popover-inner\"><div class=\"popover-content\"><p></p></div></div></div>" }); _popover.data("popover").options.content = value.message; return $(value.element).popover("show"); }); } }); });//]]> </script> 

Si alguien inteligente pudiera por favor modificar mi código para mostrarme cómo debería haberlo hecho, sería de gran ayuda. ¡Siento que estoy a punto de volverme loco!

Gracias de antemano, no puedo esperar para ver la solución 🙂


EDITAR – Este es mi código actual

Nada parece suceder en absoluto, pero siento que estoy más cerca:

CÓDIGO ACTUAL:

signup.php

  $(window).load(function(){ $("form").validate({ rules: { username: {minlength: 3, requinetworking: true}, email: {email: true, requinetworking: true, remote: {url: "./validation/checkUnameEmail.php", type : "post"}}, pass1: {minlength: 3, requinetworking: true}, pass2: {minlength: 3, requinetworking: true, equalTo: "#pass1"}, country: {requinetworking: true}, tandc: {requinetworking: true} }, 

checkUnameEmail.php

 <?php include_once(".../php_includes/db_conx.php"); $email = urldecode($_POST['email']); $result = mysqli_query($db_conx, "SELECT * FROM users WHERE email = '$email' LIMIT 1;"); $num = mysqli_num_rows($result); if($num == 0){ echo "true"; } else { echo "E-Mail-Adresse schon registriert."; } mysqli_close($db_conx); ?> 

* db_conx.php *

 <?php $db_conx = mysqli_connect("localhost", "root", "root", "membership"); //Evlauate the connection if (mysqli_connect_errno()){ echo mysqli_connect_error(); exit(); } ?> 

 $.validator.addMethod("checkExists", function(value, element) { var inputElem = $('#register-form :input[name="email"]'), data = { "emails" : inputElem.val() }, eReport = ''; //error report $.ajax( { type: "POST", url: validateEmail.php, dataType: "json", data: data, success: function(returnData) { if (returnData!== 'true') { return '<p>This email address is already registenetworking.</p>'; } else { return true; } }, error: function(xhr, textStatus, errorThrown) { alert('ajax loading error... ... '+url + query); return false; } }); }, ''); 

O

Puede utilizar el método remoto que le permite realizar comprobaciones remotas: http://docs.jquery.com/Plugins/Validation/Methods/remote

P.ej.

  $("#yourFormId").validate({ rules: { email: { requinetworking: true, email: true, remote: { url: "checkUnameEmail.php", type: "post" } } }, messages: { email: { requinetworking: "Please Enter Email!", email: "This is not a valid email!", remote: "Email already in use!" } } }); 

checkUnameEmail.php // Eg.

  <?php $registenetworkingEmail = array('jenson1@jenson.in', 'jenson2@jenson.in', 'jenson3@jenson.in', 'jenson4@jenson.in', 'jenson5@jenson.in'); $requestedEmail = $_REQUEST['email']; if( in_array($requestedEmail, $registenetworkingEmail) ){ echo 'false'; } else{ echo 'true'; } ?> 

código js

 username: { requinetworking: true, minlength: 5, remote: '/userExists' }, 

Código PHP para verificar si existe y devolver posts

 public function userExists() { $user = User::all()->lists('username'); if (in_array(Input::get('username'), $user)) { return Response::json(Input::get('username').' is already taken'); } else { return Response::json(Input::get('username').' Username is available'); } }