Advertisment

Data Validation in Silverlight 3

author-image
PCQ Bureau
New Update

We'll take a look at how you can add validation into the system so that there

is both client and server side validation of the data that is sent back before

it reaches the database.

Advertisment

The RIA SDK builds upon the LINQ model to deliver data both ways. This means

that since the model is built from the database itself, some characteristics of

the data schema are already present in the data model. This translates into some

automatic validations that come into play by default.

For instance, if you have a field which is defined as a number, the user

obviously should not be allowed to enter alphabets into it. Also, if you have

defined the length of a particular field to be a particular value, the user

should not enter strings longer than that. Luckily, such validations occur

automatically in the DataForm control when bound to the DomainDataSource.

Direct Hit!

Applies To: Web developers



USP: Validating records submitted to the
server from a Silverlight app Primary Link:

http://tinyurl.com/dcs3fj



Search Engine Keywords: Silverlight 3
Advertisment

The DataForm control has built-in validation error displays that get

triggered on the client end automatically when the data entered does not match

the data model. The error is displayed in a number of ways:

  • A validation error summary block appears near the submit buttons that lets

    the user know of all the fields that caused errors along with the exact error

    message. Each error can be clicked to take the focus to the exact field.
  • Each field with an error is highlighted in the form in both the field

    entry outline as well as the name of the field.
  • On entering any error field (or by clicking a small arrow that appears on

    its side), that particular field's error message is shown next to it in a

    small popup tip.

All validations coming from the data model are very good. However, there is

usually a need to add much more detailed level of validation into the model for

individual fields that make up the data. The first way is to simply modify the

metadata of the model itself.

Advertisment
An automatic length and number validation shown in the

summary of the DataForm.

Validations with metadata annotations



For this to work, you need to open the MetaData class that was automatically

generated when you built the DomainService (as shown in previous articles). For

instance, in our case, DomainService was called NWDomainService.cs and the

metadata class file was NWDomainService.metadata.cs. Open this up and look for

the metadata class for the entity (table) that you wish to add some validation

to. For instance, in our case the table we wish to modify is Products hence the

metadata class is ProductsMetadata.

This class contains definitions for each field in the database. You can now

start adding validations to each of these. But before you do, make sure that

these two lines of code exist at the top of the file:

Advertisment

using System.ComponentModel;



using System. ComponentModel.DataAnnotations;

Now go over to the field that you wish to add some validation to and you can

use data annotations to specify the validation. For instance, we can add a

simple validation called Range to any of the number fields like this:





public Nullable UnitsInStock;

Advertisment
Each field shows the exact error on focus or when you click

the small red arrow on the top-right corner.

Run the application and try entering some values outside of this range in the

UnitsInStock field. You will see your own validation come up in the same manner

as the automatic validations.



You can also add a number of other validations and even go ahead and change the
error message if you wish like these:

{4}", ErrorMessage="Please

use product naming convention")>



public string ProductName;





public string QuantityPerUnit;

Advertisment

These two annotations (RegularExpression and Required) allow you to specify

the respective validations to each field as well as customize the error message

that is displayed to the user when there is an error. There are many other data

annotation settings that can be used as well.

Using Custom Validations



Data annotations are quite useful in doing a specific set of validations.

However, when you wish to do a more complex type of validation you will need to

use custom code that that can bind fields against. Silverlight 3 allows creation

of custom code on the server side that is automatically shared with the code on

the client side by using the shared keyword in the name of the file. For

instance, to create a custom validator we can create a file called

MyValidations.shared.cs in the Web project. This will automatically be

accessible in the client (Silverlight) project as well. To add some validation,

open this file and enter the following:

public class MyValidations



{


public static ValidationResult UnitsValidation(double Units)


{


if (Units < 100)


return ValidationResult.Success;


return new ValidationResult("Units above stock maximum.");


}


}






Advertisment

Add the System. Component Model. Data Annotations namespace to the using

statements on the top.



Now go back to the metadata class and add the custom validation to the field you
wish like this:







public Nullable UnitsOnOrder;

Since this is a custom validation, you can actually go ahead and add this to

all other fields that are numbers as well.

There are some times when you wish for the validation of one field to be

based on the value of another. In this case, you can create a custom validation

like this:

public static ValidationResult ReorderValidation(double

ReorderLevel, ValidationContext ctx)



{


Product p = (Product)ctx.ObjectInstance;


if (ReorderLevel == (Int32)(p.UnitsInStock/2))


return ValidationResult.Success;


return new ValidationResult("Reorder Level must be exactly 1/2 of Units In
Stock");



}




In this code, the ValidationContext object gives access to the other fields

in the entered data against which you can check the current field's value and

perform a validation. Again simply add the validation to the field like this:





public Nullable ReorderLevel;

This will ensure that the data in this field will get sent to the validation

method correctly along with the rest of the current instance of the object.

As you can see, Silverlight 3 and the RIA SDK allows for fairly complex

validation scenarios quite easily and adding them to the metadata means that the

data model itself does the validation at both client and server side. Next month

we'll take a look at how you can convert this entire application to run outside

the browser and for working offline.

Advertisment