A huge part (and pain) of my A level coursework for computing was validation – it’s obviously quite important for user input. As one of my lecturers has previously mentioned, you can’t just assume a user is clever enough not to enter stupid things, and when a user breaks a program by doing so, it’s your fault.
The three main ones we had to deal with were Postcode, date, and time, since they have specific and complex formats. At the time, we were made to do them in massively huge if statement chains which the first time I wrote them were quite tedious, but luckily, for the second year, I could just copy across what I’d already written.
Looking back on this, I feel cheated. I’m rewriting all my validation methods as I don’t have my old coursework on my laptop (and it was in C++ which is close but not the same), and doing so now takes a great deal less code, after discovering the “DateTime” data type earlier this year, which ensures you can’t enter stupid dates (I think…I’ve googled this to ensure because it sounds too good to be true, but there’s no where that says anything about having to do extra validation like stopping 31/02/2011 from being entered – I’ll just test it out on the program to see if it stops it later), and the discovery of using Regular Expressions which is useful for postcodes. After finding these in C#, I looked into whether they both exist in C++. Yes. Yes, they do.
As I haven’t actually said what a RE is, basically it’s a definition of the format in which the string must be entered using specific syntax. This is where I can see that the maths module I had to do this year is important, as I learned about them in that module – this doesn’t mean I remember -all- of the syntax, but it’s useful to know how they work. A useful website which I will be favouriting is the Regular Expression Library, where I got my postcode RegEx from.
I can see why you’re made to do all the validation, as at the time both of those may have been too complex for what was need-no that’s a lie, both of them are really easy to use…I can see why because it does make you think specifically how you need to validate everything, but at the same time I can’t help thinking “I spent a good few hours working out the algorithm, making the pseudo code/flow chart, and finally programming each of these methods” when it’s literally taken 3 lines of code to see if a postcode fits in a regular expression. I love moments like these.
For those who need to use regular expressions, all you need to do is add the library System.Text.RegularExpressions and set up your regular expression as shown in the screenshot above:
Regex Name = new Regex(“your regular expression here”);
if(Name.IsMatch(string))
{
whatever you want to happen here
}
Hope that helps.




