Validation and error handling points
I have been writing a form today to send off emails with a PHP back-end. All day I have been dealing with validation and trying to cover all the bases (so all your bases remain belonging to YOU).
Things to keep in mind when validating data.
Things to keep in mind when validating data.
- Presence - if the field is mandatory, validate that it has a value.
- Always give some visual way of marking a field as mandatory.
- Size - check the size of the input i.e. that it is less than a certain number of characters.
- Do this for all values, whether they are coming from an input, text area, checkbox or radio button. One way a site can be attacked is for a malicious sender to ignore your HTML form and POST their own massive values.
- Escape and sanitise data before you use it to prevent cross site scripting or SQL injection attacks. Do this before you:
- Save to a DB.
- Output back to HMTL.
- Write to a file.
- Send to an email.
- Send it to another part of your back-end for further processing.
- Type - check that an input is an integer or double or boolean as required.
- Format - check that input matches a required format, like a phone number or email etc.
- Can be helped by using input masks, but you still need to validate that the data you received matches the mask on the server side.
- Value - check input against your own business logic. For example:
- Is a number within a given range.
- Does the string match an element in a known list of choices.
- Related - apply any validation that requires examining multiple fields. For example, if country, state and postcode are given, make sure that they are a valid combination.
- Server side first.
- Client side validation is often easier, but server side validation is more important because javascript can be disabled or ignored completely if a malicious sender simply POSTS their own requests.
- Consider how to return errors in a such a way that they can be easily communicated back to the user on the interface.
- Client side second
- While server side is more important, client side validation makes for a faster and more responsive user experience because you can point out errors before the user ever hits SEND.
- Consider things such as how to present errors to users and how mark things like dynamic business rules (where field A is only mandatory if field B is given a value).