Applying Custom Validation to a Field in LightSwitch Visual Studio 2012

Applying Custom Validation to a field

A validation rule is a condition that the data in our application must conform to. If you can add one or more validation rules to a table then an error appears if a user adds or changes data in a table that violates the rule. Before a user can commit the data, the validation error must be fixed.

LightSwitch includes several built-in validation rules that we can use without writing any custom code. However we can define custom validation rules by writing code.  

How we can apply a Custom Validation to a Field

Step 1

Open the Solution Explorer.

Image 1

solex.jpg

Step 2

In the Solution Explorer, double-click or right-click on the table to open it.

Image 2

tabopen.jpg

Step 3

The table opens in Data Designer.

Image 3

employee table.jpg

Step 4

In the table, choose the field that you want to validate.

Image 4

employee table1.jpg

Step 5

Open the Property Window.

Image 5

prowin.jpg

Step 6

In the Property Window, choose the Custom Validation link.

Image 6

prowin1.jpg

Step 7

The Code Editor opens that consists of a method that's named FieldName_Validate(). Add the Validation code to this method.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.LightSwitch;

namespace LightSwitchApplication

{

    public partial class Employeetab

    {

        partial void ProductDate_Validate(EntityValidationResultsBuilder results)

        {

            // results.AddPropertyError("<Error-Message>");

            if (this.ProductDate > DateTime.Today)

            {

                results.AddPropertyError("Product date cannot be later than Today");

            }

        }

    }

}

 

Output

When the if condition is true we get the following output:

noerr output.jpg


When the if condition is false we have:

outputerr.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all