Prince
Prince

Reputation: 1192

Check $_POST data with jquery before submitting the form

I have a form that sends the store the First Name of the user in a database. I was checking the information send by the user using regex in php. To make my project more interactive, I decided to validate the information jQuery before sending it to PHP.

My Project looks like this:

<script type="text/javascript" src="jquery-2.2.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js" type="text/javascript"></script>

<body>
    <form >
        <div>
            <label>First Name</label>
            <input name="firstname" type="text">
        </div>
        <div>
            <input type="submit">
        </div>
    </form>
</body>
</html>

<script>
    $(document).ready(function() {
        
        $("form").submit(function (e) {
            
            var firstname = $(this).find('input[name="firstname"]').val();

            var regex = /^[A-Za-z0-9 \-']+$/;//Only numbers, Letters, dashes, apostrophes and spaces are accepted
            if(regex.test(firstname)){
                alert('Valid Name.');
            }else{
                alert('Invalid Name.');
                e.PreventDefault();
            }
        });
    });
</script>

Now I have 2 questions:

  1. Is it really need to check the First Name in PHP again before storing the data in the database ? (To improve security)
  2. How can I submit the form right after the alert('Valid Name.'); ?

Thanks for providing your help.

Upvotes: 1

Views: 2229

Answers (3)

Bronson
Bronson

Reputation: 91

Firstly you should ALWAYS validate server side for form submission, especially if you are passing those value along to a DB - SQL injection, the struggle is real.

As for the form submission flow you can...

return true

... after the valid name alert and the form to submit as it normally would.

Since you already have bound to that submit event, It would be even better for the user if you submitted the form via ajax, and providing feedback if the server validation fails. Thus the user never leaves the page and you are able to handle both client and server validation.

Take a look at ParsleyJS - http://parsleyjs.org/ - w00t!

Upvotes: 0

dios231
dios231

Reputation: 726

First of all have in mind that the validation of users input is implementing at the server side of an application only!!! You can not validate input data at client side with JS because it can be passed very easy(either by disabling javascript or by using tools like Curl).

However you can increase user experience like validate an input before submitting the form or inform the user that forgot to fill in an input.

To inform the user about a not fill in input you can just use the new html 5 attribute required like above

Username: <input type="text" name="usrname" required>

the required attribute will not let the user submit the form unless he had filled the associated input.

Also you can use the maxlength attribute to address a use case like "A password must have X max letters.

Password: <input type="password" name="pass" maxlength="8" size="8"><br>

How to validate input at server side

There are many techniques for this and you can find all of them here at Stackoverflow. Ι will refer the top voted post How can I prevent SQL injection in PHP? which answer exactly your question.

Just two bullets that compact the above post that i suggest you read otherwise

  • Always escape your data

  • Use mysqli instead of mysql

How can I submit the form right after the alert('Valid Name.'); ?

this is very easy just use this code

    <form action="action_page.php" method="post">
    <div>
        <label>First Name</label>
        <input name="firstname" type="text">
    </div>
    <div>
        <input type="submit">
    </div>
</form>

the above code will "send" user's input for process at action_page.php using POST method, where you can read using $_POST supergloba table like $firstname = $_POST['fistsname'] etc.

Upvotes: 1

Harshad Hirapara
Harshad Hirapara

Reputation: 462

TRY This

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.js" ></script>
     <script type="text/javascript" src="jquery-2.2.3.min.js"></script>
        <script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js" type="text/javascript"></script>

    <body>
        <form >
            <div>
                <label>First Name</label>
                <input name="firstname" id="first_name" type="text">
            </div>
            <div>
                <input type="submit">
            </div>
        </form>
    </body>
    </html>

    <script>
    jQuery.validator.addMethod("firstName",function(value,element,param)
    {
  if(this.optional(element))
    {//This is not a 'required' element and the input is empty
      return true;
    }

  if(/^[A-Za-z0-9 \-']+$/.test(value))
    {
      return true;
    }

    return false;

},"Please enter a valid First Name");

$(function()
{
    $('#myform').validate(
      {
      rules:
        { 
          first_name:{ required:true, firstName:true }
        }
      });

});
    </script>

Upvotes: 0

Related Questions