dev in the making

game development, maya and code by brainzizi

Posts Tagged ‘validation

Client validation in Silverlight

Validation is the single most important thing in user interfaces. Go write an app. Like a simple calculator. Have textboxes and buttons and things like that. Does it work for 5+5? Yes? Good. Now see what your app thinks about the sum of “aklsgfjgbas” and “asjkhdgbas”. Preventing that and far more worse things is validation.

My validation mind map looks something like this. There are two types of validation: prevention and correction. Preventing would be to not let the user enter things like that at all. Correction would be if a user enters things he shouldn’t you just warn him. Maybe not even let him press the ok button or something. I use prevention in most cases, and that’s the next topic. Also formally there are 2 types of validation client side and server side. I’ll be talking about client side validation.

ASP.net has some controls which hack into javascript to do basic validation. I hate javascript. HTML also. That’s why I use Silverlight… Ok ’nuff of that.
Silverlight’s textbox is a plain one, like in WinForms but still a bit different. One thing different from WinForms is that WinForms can only run on Windows. Silverlight on the other hand runs on everything with a browser. And that’s the problem, you don’t have the WinKey on Apples, the keys are inconsistent on various platforms. When you do my type of validation you should hook a method on the KeyDown event of a textbox and check if the ascii is ok. And if it’s not a weird char allow it. First, you can’t get ascii of a char from the KeyPressEventArgs or whatever it’s called, you can get the platform specific code or an Key enumeration. Not good. Second that doesn’t prevent copy/pasting weird stuff in the text box. The way I solved it is hooking a method on TextChanged and checking all chars for weird stuff.
Example for allowing valid email chars below:

MyTextBox.TextChanged += (sender, e) =>
{
    foreach (char c in ret.Text.ToCharArray())
    {
        if (!Char.IsLetterOrDigit(c) && c != '@' && c != '.' && c != '_' && c != '-')
        ret.Text = ret.Text.Replace(c.ToString(), "");
    }
};

If you think that this is not C#, google lambda expressions. I’ll write a post about it soon I hope.

Advertisements

Written by brainzizizi

04.16.2009 at 13:04