Let’s today understand Data Validation

The first principle: Assume no data to be valid.
Second principle : The rigidness of your rules will testify the validness of the data.

First, decide the parameters that you need to weigh your inputs on:

1. Range of Value
2. Value precision
3. Format
4. Length
5. Type

Third principle: Decide your strategy and follow it.

Now there are two philosophies in validating the data:
1. Negative test cases i.e. all those values for which validation test should fail.
2. Positive test cases i.e. all those values for which validation test should pass. (I recommend this 🙂 )

Some key points to keep in mind:

1. Strong-data-typing: Numbers should be stored in Integer, Double, Float or a relevant data type rather than storing in a Generic data type. This besides validating the data, also enhances the performance (read memory allocation).

2. Not just client side validation: Validating at client side (using JavaScript/VbScript) is not just sufficient. Use appropriate server-side validations. However, this does not mean not validating at client side – it helps reducing server-side round trips.

3. Free-text Fields: Multiline fields (or free-text fields) should be checked before storing. They may contain some unwanted code like C# snippet, or a SQL query itself. Test it against SQL Injection. Also in ASP.NET applications, make sure that HTML inputs do not crash the application. An input like <i> may do disasters. Prefer to HTML encode data before processing it.

1. In the page directive, add ValidateRequest = “false”
2. Encode using HtmlEncode
3. Use RegEx to remove Html Content

4. Upload/Download Paths: While making a Chat Engine (using WCF & WPF) that uses username/password and photograph of a user to log in, you may take path of the photograph placed on his machine. While someone wants to view it, it may not be accessible (since its on a network). Make sure a correct strategy is used and paths are validated before processing.

5. Special Characters in WebServices: WebServices do not allow special characters (like heart, diamonds) to be passed through the wire even when stored inside a string. Make sure that they are converted into Binary/Hex or other format before transmitting.

6. URLs: Urls/Cookies/QueryStrings should not be without encoding. Validation needs to be done for length, range, format and types.