How to: Validate Data

You can apply validation rules to an entity or table to ensure that properly formatted data is written to the data source. A validation rule is a condition or constraint that the data in your application must comply with. You can add one or more validation rules to an entity or table in LightSwitch. If a user adds or changes data and that data does not comply with the validation rules, LightSwitch displays an error. Before a user can commit the data, the validation error must be fixed.

The following illustration shows a validation error message.

Validation error message

LightSwitch includes several built-in validation rules. You can configure these rules and apply them to an entity or a table without writing any code. You can also use code to define custom validation rules.

This topic contains the following sections:

  • Applying Predefined Validation Rules to a Field

  • Applying Custom Validation Rules to a Field

  • Applying Custom Validation Rules to Data in a Screen

  • Applying Validation Rules That Run When Data Is Saved

link to video For a related video demonstration, see How Do I: Write business rules for validation and calculated fields in a LightSwitch Application?.

Applying Predefined Validation Rules to a Field

LightSwitch includes several built-in validation rules that you can use without writing any custom code. You can apply these rules to individual fields of data or to any kind of update that users make to data in a screen.

To apply a predefined validation rule to a field

  1. In Solution Explorer, double-click the entity or table to which you want to apply validation rules.

    The entity or table opens in the Data Designer.

  2. In the Data Designer, select the field that you want to validate.

  3. In the Properties window, in the Validation section, set the value of any the properties.

    For information about the validation properties, see Reference: Data Designer Properties..

Applying Custom Validation Rules to a Field

You can define custom validation rules by writing code. You can specify when these validation rules are enforced by LightSwitch. For example, you could specify that a validation rule on a field is enforced immediately after a user types a value. Alternatively, you could specify that an entity or a table is evaluated only after all of its fields contain a value. This model makes sense when the validity of a value in one field relies on a valid value in another field in the same entity or table.

To apply a custom validation rule to a field

  1. In Solution Explorer, double-click the entity or table to which you want to apply validation rules.

    The entity or table opens in the Data Designer.

  2. In the Data Designer, select the field that you want to validate.

  3. In the Properties window, click Custom Validation.

    The Code Editor opens and generates a method named FieldName[_Validate].

  4. Add validation code to the FieldName[_Validate] method.

    To enforce a validation rule immediately after a user provides a field value, call the AddPropertyError method of the results parameter.

    The following example displays a validation message after a user sets the ShippedDate field of the Order entity to a date that is later than today.

    Private Sub ShippedDate_Validate(results As EntityValidationResultsBuilder)
        If Me.ShippedDate > DateTime.Today Then
            results.AddPropertyError _
                ("Shipped date cannot be later than today")
        End If
    
    End Sub
    
    partial void ShippedDate_Validate(EntityValidationResultsBuilder results)
    {
        if (this.ShippedDate > DateTime.Today)
        {
            results.AddPropertyError("Shipped date cannot be later than today");
        }
    
    }
    

    Notice that you can highlight other properties for validation. For example, you could write validation code that runs when a user changes the zip code of a customer. If you pass the City property as a parameter to the AddPropertyError method, LightSwitch will highlight the City field. Your validation error message text could prompt the user to type the name of a city that matches the new zip code.

    Note

    By default, updates cannot be committed to a data source until they conform to the validation rules. If you want to enable users to commit unevaluated updates, use the AddPropertyResult method instead of the AddPropertyError method. For the second parameter of the AddPropertyResult method, pass in either ValidationSeverity.Informational or ValidationSeverity.Warning.

    To enforce a validation rule on an entity or a table, for example, when a user modifies a value in a field that relies on a valid value in another field, call the AddEntityError method of the results parameter. The following example compares the value of the RequiredDate field to the value of the OrderDate field. If the order date is later than the required date, this code displays a validation error message.

    Private Sub RequiredDate_Validate(results As EntityValidationResultsBuilder)
        If Me.RequiredDate < Me.OrderDate Then
            results.AddEntityError _
                ("Required data cannot be earlier than the order date")
        End If
    
    End Sub
    
    partial void RequiredDate_Validate(EntityValidationResultsBuilder results)
    {
        if (this.RequiredDate < this.OrderDate)
        {
            results.AddEntityError
                ("Required data cannot be earlier than the order date"); 
        }
    
    }
    

Applying Custom Validation Rules to Data in a Screen

You can specify custom validation rules that apply to a whole screen by adding custom code to the <entity or table name>[_Validate] method in the screen code file. Your custom code runs when a user modifies any data in the screen (for example, adds or deletes data). These rules run before the data can be saved.

To apply a custom validation rule to data in a screen

  1. In Solution Explorer, double-click the screen for which you want to specify a validation rule.

  2. At the top of the Screen Designer, click Write Code.

    The Code Editor opens.

  3. On the Declarations menu, select <entity or table name>[_Validate].

    A code block named <entity or table name>[_Validate] appears in the code file.

  4. Add your custom validation code to the <entity or table name>[_Validate] method.

    To enforce a validation rule after a user adds, deletes, or updates a row of data, call the AddScreenError method of the results parameter.

    The following example prevents the deletion of customers who are located in the United States.

    Private Sub Customers_Validate _
        (results As Microsoft.LightSwitch.Framework.Client.ScreenValidationResultsBuilder)
        If Me.DataWorkspace.NorthwindData.Details.HasChanges Then
            Dim changeSet As EntityChangeSet = _
                Me.DataWorkspace.NorthwindData.Details.GetChanges()
    
            Dim entity As IEntityObject
    
            For Each entity In changeSet.DeletedEntities.OfType(Of Customer)()
    
                Dim cust As Customer = CType(entity, Customer)
                If cust.Country = "USA" Then
                    entity.Details.DiscardChanges()
                    results.AddScreenResult("Unable to remove this customer." & _
                        "Cannot delete customers that are located in the USA.", _
                         ValidationSeverity.Informational)
                End If
    
            Next
        End If
    
    End Sub
    
    partial void Customers_Validate(ScreenValidationResultsBuilder results)
    {
        if (this.DataWorkspace.NorthwindData.Details.HasChanges)
        {
            EntityChangeSet changeSet =
            this.DataWorkspace.NorthwindData.Details.GetChanges();
            foreach (IEntityObject entity in changeSet.DeletedEntities.OfType<Customer>())
            {
                Customer cust = (Customer)entity;
                if (cust.Country == "USA")
                {
                    entity.Details.DiscardChanges();
                    results.AddScreenResult("Unable to remove this customer. " +
                    "Cannot delete customers that are located in the USA.",
                    ValidationSeverity.Informational);
                }
            }
        }
    
    }
    

    Note

    By default, updates cannot be committed to a data source until they conform to the validation rules. If you want to enable users to commit unevaluated updates, use the AddScreenResult method instead of the AddScreenError method. For the second parameter of the AddScreenResult method, pass in either ValidationSeverity.Informational or ValidationSeverity.Warning.

Applying Validation Rules That Run When Data Is Saved

You can apply custom validation rules when a user saves data or when your code calls the SaveChanges() method of a data source. This kind of validation runs exclusively on the server tier.

To apply validation rules that run when data is saved

  1. In Solution Explorer, double-click the entity or table to which you want to apply validation rules.

  2. In the command bar of the Data Designer, click the arrow next to the Write Code button and then click entity or table name[_Validate].

    The Code Editor opens and generates a method named entity or table name[_Validate].

  3. Add your custom validation code to the entity or table name[_Validate] method.

    Call the AddEntityError method of the results parameter.

    The following example checks the credit status of a customer when a user saves a sales order. If the customer’s credit has not yet been approved by the financing department, a ValidationException is thrown.

    Private Sub Orders_Validate _
        (entity As Order, results As  _
         Microsoft.LightSwitch.EntitySetValidationResultsBuilder)
        If Not CustomerCreditApproval(entity.Customer) Then
            results.AddEntityError("Customer Credit has not yet been approved")
        End If
    
    End Sub
    Private Function CustomerCreditApproval(ByVal entity As Customer) As Boolean
        'Some custom code to check the customer’s credit status.
        Return True
    
    End Function
    
            partial void Orders_Validate
                (Order entity, EntitySetValidationResultsBuilder results)
            {
                if (!CustomerCreditApproval(entity.Customer))
                {
                    results.AddEntityError
                        ("Customer Credit has not yet been approved");
                }
            }
    
            private bool CustomerCreditApproval(Customer entity)
            {
                //Some custom code to check the customer's credit status.
                return true;
            }
    
    

    Note

    By default, when the exception is thrown, an error message is displayed and the data remains in the current change set. If you want to change this behavior, you can handle the ValidationException in your code.

See Also

Tasks

How to: Handle Data Events

How to: Define Data Fields

Concepts

Performing Data-Related Tasks by Using Code

Working with Data-Related Objects in Code

Writing Code in LightSwitch

Other Resources

Overview of Data Validation in LightSwitch Applications

Data: The Information Behind Your Application