Data Binding in Silverlight with RIA and Entity Framework (Validating Input Data)


Validation is an integral part of software development. In Silverlight the validation approach has been changed or you can say evolved from version 2. So this article will highlight the options available for validation with a continuation of the StatesOfIndia application.

Article Series

Source Code and Demo Link

Hosted Application : Live Sample

Source Code : StatesOfIndia

Extending StatesOfIndia Application

In Continuation to the SOI application we will add validation to the user input; esssentially I want to do validation using the following logic.

Basic Validation

  • State Name Mandatory and Length should not exceed more than 15
  • Data type Validation for Population, Literacy, Number of Districts, and Area that should allow Numeric Entry only
  • Website URL Validation
  • Define Population, Literacy Range

Adv. Validation

  • Cross Check State Name whether it exists in Database (Cross Property Validation)

Validation In RIA With Silverlight

There are many ways of validating the user input; either you can do it at the client side without a server round-trip or request or else do validation at the server side or async validation. It depends on your choice and scenario. Prior versions of Silverlight primarily dependend on Exception Based validation and with current available solution it does not make sense to discuss so I have skipped Exception Based Validation.

Silverlight 4 exposes basically following methods of validation

  • Using Metadata Attribute
  • Code Behind Approach (Can be used at Client side using Async Operations or else Server side only)
With Attribute Metadata

As mentioned earlier the validation rule can be defined at entity level and their member. To do so make sure that you have selected the Metdata generation option while adding the DomainService. This option will add a metadata class "DomainService_SOI.metadata.cs". Checking the class file we can find the the entity and its members.

Data Binding in Silverlight with RIA and Entity Framework – Part 3 ValidatingData) Data Binding in Silverlight with RIA and Entity Framework – Part 3 ValidatingData)

Now suppose I want to enforce stateName as mandatory and the character length of the state should not exceed 15 then:

  1. [Required(AllowEmptyStrings=false,ErrorMessage="State Name cannot be empty")]
  2. [StringLength(15)]
  3. public string StateName { getset; }


Now build your application and check the generated code at client side silverlight project.


Data Binding in Silverlight with RIA and Entity Framework – Part 3 ValidatingData)

PROPAGATED CLIENT SIDE VALIDATION CODE
  1. /// <summary>
  2. /// Gets or sets the 'StateName' value.
  3. /// </summary>
  4. [DataMember()]
  5. [Required(ErrorMessage="State Name cannot be empty")]
  6. [StringLength(15)]
  7. public string StateName
  8. {
  9. get
  10. {
  11. return this._stateName;
  12. }
  13. set
  14. {
  15. if ((this._stateName != value))
  16. {
  17. this.OnStateNameChanging(value);
  18. this.RaiseDataMemberChanging("StateName");
  19. this.ValidateProperty("StateName"value);
  20. this._stateName = value;
  21. this.RaiseDataMemberChanged("StateName");
  22. this.OnStateNameChanged();
  23. }
  24. }
  25. }


If you notice then you will find the attributes we added to the model metadata member is propagated to client side automatically. We can show a custom error message by providing the Error Message Attribute as bellow.

  1. [Required(AllowEmptyStrings=false,ErrorMessage="State Name cannot be empty")]


Following are some of the other attributes for property level validation defined in System.ComponentModel.DataAnnotations namespace.

So as mentioned above the SOI application basic validations can be achieved with the following attributes.

State Name Mandatory and Length should not exceed more than 15

  1. [Required(AllowEmptyStrings=false,ErrorMessage="State Name cannot be empty")]
  2. [StringLength(15)]
  3. public string StateName { getset; }

Since the validation needs to be fired from the textbox leave event, we need to do some ground clearance work although against wish Confused smile. Check with my last Blogpost.


Website URL Validation

  1. [DataType(DataType.Url)]
  2. public string Website { getset; }

Define Population ,Literacy Range

  1. [Range(0,100)]
  2. public Nullable<int> Literacy { getset; }


Data type Validation for Population, Literacy, Number Of District and Area that should allow Numeric Entry only. Since we need to restrict the user while entering the value I have handled it in code behind in the KeyDown event.

Custom attribute Validation

Although the default attribute provides nearly all standard ways to validate, sometimes custom validation is unavoidable. For e.g. here the wiki info content must be more than 3 words. To add custom validation keep the following points in mind.

  • Add a class which will contain the validation logic at server side
  • make sure that your class will have a shared.cs extension so that the validation can be propagated to the client side

Lets do it. Add class StateValidations.shared.cs to the Server side project of the solution.

Data Binding in Silverlight with RIA and Entity Framework – Part 3 ValidatingData)

The custom validation check is a simple C# code named "ValidInfo" which is a static member that takes ValidationContext as an argument other than the value needed to be checked. ValidationContext represents state and service of the object to be validated. Once the validation has succeeded it returns a ValidationResult object.

  1. namespace StatesOfIndia.Web.Shared
  2. {
  3. public class StateValidations
  4. {
  5. public static ValidationResult ValidInfo(string description, ValidationContext context)
  6. {
  7. //Validation Logic
  8. if (String.IsNullOrEmpty(description))
  9. {
  10. return ValidationResult.Success;
  11. }
  12. string[] words = description.Split(new char[] { ' ''\t''\n''\r', },
  13. StringSplitOptions.RemoveEmptyEntries);
  14. if (words.Length > 3)
  15. {
  16. return ValidationResult.Success;
  17. }
  18. //return Validation Error
  19. return new ValidationResult("The Wiki Info must be meaningful.",
  20. new string[] { "WikiIntro" });
  21. }
  22. }
  23. }


Once you have built the project, check with the Silverlight client side project. The Generated Code stub will now have the same shared.cs.

image

To implement the custom validator let's move to our TasksDomainService.metadata.cs at server side project and add following attribute to the WikiInfo property.

  1. [CustomValidation(typeof(StateValidations),"ValidInfo")]
  2. public string WikiIntro { getset; }


When the CustomValidation attribute is applied to a property, the attribute is invoked whenever a value is assigned to that property. When it is applied to a method, the attribute is invoked whenever the program calls that method. When it is applied to a method parameter, the attribute is invoked before the method is called. A more detailed article can be found here.

Let's Run the application and check with the result.

Data Binding in Silverlight with RIA and Entity Framework – Part 3 ValidatingData)

Asynchronous Validation to check weather State Exist against database

In an SOI application it's pretty normal to check whether it exists in the database before adding it to the collection. Instead of validating it on button click, it will be nice if the validation is done on the fly, once the user leaves the Textbox. For the validation to succeed it needs to hit back to the database collection and needs to verify.

Ahhh its quite exciting. Let's check.

  • Add a new Method/Operation to domain service class "DomainService_SOI.cs" , Named "IsStateExist". As you can find in the method bellow that has an [INVOKE] attribute which lets the operation run without deferred execution. More details can be found Here)
  1. [Invoke]
  2. //Custom Validation for Async Operation
  3. public bool IsStateExist(string stateName)
  4. {
  5. bool isStateExist = false;
  6. isStateExist = GetStates().Any(state => state.StateName == stateName);
  7. return isStateExist;
  8. }
  • Add a custom validator method as shared code, as we have done in the above "ValidInfo" case.
  1. public static ValidationResult AsyncValidateState(string stateName, ValidationContext valContext)
  2. {
  3. ValidationResult error = new ValidationResult(
  4. "State with specified name already exists",
  5. new string[] { valContext.MemberName });
  6. //Code For Client Side silverlight project
  7. #if SILVERLIGHT
  8. DomainService_SOI context = new DomainService_SOI();
  9. InvokeOperation<bool> IsExist = context.IsStateExist(stateName);
  10. IsExist.Completed += (s, e) =>
  11. {
  12. if (!IsExist.HasError && IsExist.Value)
  13. {
  14. Entity entity = (Entity)valContext.ObjectInstance;
  15. entity.ValidationErrors.Add(error);
  16. }
  17. };
  18. #endif
  19. return ValidationResult.Success;
  20. }
  1. [CustomValidation(typeof(StateValidations), "AsyncValidateState")]
  2. public string StateName { getset; }

Let's run the application and let the validation do it's work.

Data Binding in Silverlight with RIA and Entity Framework – Part 3 ValidatingData)

Conclusion

Hope this article gives you a fair idea about data validation. Keep Learning .Smile.

Up Next
    Ebook Download
    View all
    Learn
    View all