The intval() function casts user input as an integer, and defaults to zero if the input was a non-numeric value.
We then check to see if the value ended up as zero.
If it did, we'll save an empty value to the database.
Otherwise, we'll save the properly validated zipcode.
Server-side validation is more secure but often more tricky to code, whereas client-side (Java Script) validation is easier to do and quicker too (the browser doesn't have to connect to the server to validate the form, so the user finds out instantly if they've missed out that required field! In this tutorial we'll build a simple form with client-side Java Script validation.
We can fall back to using these methods when there's a range of acceptable input.Our validation script will ensure that the user enters their name before the form is sent to the server. Try pressing the Send Details button without filling anything in the "Your Name" field.You might like to open the source code for this form in a separate window, so that you can refer to it throughout the tutorial.For instance, to check "my-zipcode" field, we might do something like this: Since the `maxlength` attribute is only enforced by the browser, we still need to validate the length of the input on the server.If we don't, an attacker could manually submit a form with a longer value.