lisovaccaro
lisovaccaro

Reputation: 33996

How to prevent form from submitted based on PHP value?

I'm using Ajax to test if the Username on a Register form is too short.

Right now it just does this:

if (str.length<6)
  { 
  document.getElementById("txtHint").innerHTML="Too short";
  return;
  } 

How do I add an action above that doesn't let the user submit?

<form action="/insert/insert-user.php" method="post">
    <input type="text" name="user"  onkeyup="showHint(this.value)"/>

Upvotes: 0

Views: 76

Answers (3)

Chibuzo
Chibuzo

Reputation: 6117

You may try adding a form name and onsubmit event to your form.

<form name="formName"action="/insert/insert-user.php" method="post" onsubmit="validate()">

function validate() {
    if (document.formName.user.value.length < 7) {
        // Display your message in your division 
         return false;
    }
}

You must also repeat the check in php since the user may have Javascript disabled and for security measure:

if ($_POST['your_submit_button']) {
    if (strlen($_POST['user']) < 7) {
        $submit = false;
        die ("<div style='color: red;'>Too short</div>"); 
    }
}

Upvotes: 0

Assad Ullah
Assad Ullah

Reputation: 785

Give your error div a class lets say 'error' and on submitting the form call another function in which you check the if error class have text by JQuery. If the class have the text just return false and your form will not be submitted

Upvotes: 0

Jason Fuller
Jason Fuller

Reputation: 127

In the CheckUserName function, add your ajax code and return true or false. If It's false, it won't submit.

  <form action="/insert/insert-user.php" onsubmit="CheckUserName()" method="post">

Upvotes: 1

Related Questions