AJAX process with field validation

Viewed 52

Whole AJAX code:

function checkEmail() {
  // var myForm = $("#mainForm").serialize();
  var fname = $("#first").val();
  var lname = $("#second").val();
  var email = $("#email").val();
  var password = $("#password").val();
  var repass = $("#en").val();
  if(fname && lname && email && password && repass) {
    jQuery.ajax({
      url: "connection.php",
      data: {
          fname:fname,
          lname:lname,
          email:email,
          password:password,
          repass:repass
      },
      type: "POST",
      success:function(data){
  $("#emailExists").show();
  $("#email").css("border","2px solid green");
  $("#no").css("visibility","hidden");
  $("#yes").css("visibility","visible");
  if(data){
    $("#email").css("border", "2px solid red");
    $("#no").css("visibility","visible");
    $("#yes").css("visibility","hidden");
    }else
    {
    $("#email").css("border", "2px solid green");
    $("#no").css("visibility","hidden");
    $("#yes").css("visibility","visible");
    window.location.href = 'home.php';
    }
  $("#emailExists").html(data);
  },
  error:function (){
  }
  });
   }
}

Here's a signup form validation, and an email exists system using PHP and AJAX. I have a problem with AJAX. So, on the click of the signup button, the AJAX should only run (to check if email already exists using PHP data and display error message) if every field is filled up, and if the password length is greater than or equal to 6 AND if the password is equal to the repass (re-enter password).

So, initially, in the success function, I wrote:

if(fname && lname && email && password && repass) {

And all the code under it. But it should also only call success function, if password value is greater than or equal to 6, and also if password is equal to repass. And if only every field is filled up AND password >= 6 and password == repass, it should take the user to the homepage (home.php), otherwise it should stay there, display error messages, then user will change to the correct details and it'll redirect to homepage. (I already have a window.location.href = 'home.php' in the else statement, so that's taken care of).

So for that I'm trying this code:

if(fname && lname && email && password && repass && password.val() >= 6 && password == repass) {

But it isn't working. What should I do? Please give a solution. Thanks a lot!

1 Answers

As said here, use this:

password.length >= 6

So:

var password = $("#password").val();
if (fname && lname && email && password && repass && password.length >= 6 && password == repass) {

But form validation is more than just checking if it's filled or password length. You can use RegEx to validate some objects.

Related