HTML Form Validation Using PHP

Discussion in 'Web Design and Development' started by kolax, Jul 11, 2012.

  1. kolax macrumors G3

    Mar 20, 2007
    I have some HTML forms that I want to validate using PHP. I've been told that I should validate them by posting them to a separate PHP file, rather than including the PHP code in the HTML document (as someone could save the source, amend the PHP validation to be able to input anything).

    Any pointers on validating the following would be great:
    - A form to just have letters and numbers
    - A date form to be the correct format (dd/mm/yyyy)
    - A form not to be blank

    If this is correct, then proceed to add these to the database.

    However, with having validation outside of the HTML itself, how do I give an error message highlighting which form had data in an incorrect form?
  2. Jamesbot macrumors member

    Jun 19, 2009
    you'll want to create whats called a sticky form.

    basically you'll need to create a php file instead of your regular html-only file that behaves differently if its responding to a POST rather than a GET request.

    your validations can then exist in the same file as your form. you'll need to use some php functions and likely some regular expressions to perform the validations on the POST parameters.

    if the POST passes validation then continue, otherwise re-render the form with errors highlighted.

    the benefit of doing it this way as opposed to a separate php script is the user shouldnt be presented with an entirely blank form if only one out of many fields fails validation.


    oh and php source should never show up in the browser. it gets parsed into html before leaving the server.
  3. kolax thread starter macrumors G3

    Mar 20, 2007
    Thanks for the pointers - I'll try doing what you suggested.

Share This Page