简体   繁体   中英

Form validation - is jQuery validation sufficient and how to neatly validate data in PHP?

I have a form (right now only one, but there will be more with similar parameters) and I validate it using jQuery Validation ( it is too big word, I validate only one field using jQV), this form is send using AJAX. I have in this form 5 inputs:

  • text input: username , which is validated by separate PHP script remotely - it checks if this user exists in database of different site and if so, also checks if this user has some specified data, but this is not really important

  • 2 times radio buttons (i mean 2x 2 radio buttons) which are validated in PHP (code later)

  • 2 times PickAColor forms, which are also validated using PHP only with regexp for hexcolors

And I have a question. Is there any way to check this data in PHP in more, well, sophisticated way? Because, as I said, I validate them in similar way:

if($period != "3month" && $period != "7day") {
  echo '<div class="alert">Wrong period!</div>';
  exit;
}

Actually this form I am writing right now is rather short, but I also have some really big ones, and if 's like this one above can take even 50 lines, and that pretty sucks. Most of them has similar expressions inside if , which means that I check if value sent by form is on the list of possible options provided by form (someone can change value parameters in Firebug and call himself hacker...). It's complicated and I don't know how to said that, but I think you understand me. So, once again - is there any sense to validate it in PHP and if so, is there any better way to validate it? Or maybe you have some other suggestions? Thanks a lot for your help.

Man you have to think your users can submit anything there, and to make the code clearer and more MVC oriented (and reusable) you need your validations in the app side, and generic functions in jQuery to just display errors to your users, so I would recommend you to do ajax post with the form sent to your php application, to an api controller that recives the form values, validates using the model and returns the object with the jew form values (if you need to clean up) and any error per field, then you just output in json :

{
    errors: {
        name: "Already used name",
        field2: "Some bad text provided"
    }
}

Then you just loop through the errors and set to the already existent placeholder of each error text like

<spam id="name-error" class="error"></spam>
<input type="text" name="name" value=""/>

Then you have a validation code that you can reuse when the form is submitted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM