0 out of 3 rated this helpful - Rate this topic

ValidationRule Class

Provides a way to create a custom rule in order to check the validity of user input.

Namespace:  System.Windows.Controls
Assembly:  PresentationFramework (in PresentationFramework.dll)
public abstract class ValidationRule

The ValidationRule type exposes the following members.

  Name Description
Protected method ValidationRule() Initializes a new instance of the ValidationRule class.
Protected method ValidationRule(ValidationStep, Boolean) Initializes a new instance of the ValidationRule class with the specified validation step and a value that indicates whether the validation rule runs when the target is updated.
Top
  Name Description
Public property ValidatesOnTargetUpdated Gets or sets a value that indicates whether the validation rule runs when the target of the Binding is updated.
Public property ValidationStep Gets or sets when the validation rule runs.
Top
  Name Description
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method ToString Returns a string that represents the current object. (Inherited from Object.)
Public method Validate When overridden in a derived class, performs validation checks on a value.
Top

When you use the WPF data binding model, you can associate ValidationRules with your binding object. To create custom rules, make a subclass of this class and implement the Validate method. Optionally, use the built-in ExceptionValidationRule, which catches exceptions that are thrown during source updates, or the DataErrorValidationRule, which checks for errors raised by the IDataErrorInfo implementation of the source object.

The binding engine checks each ValidationRule that is associated with a binding every time it transfers an input value, which is the binding target property value, to the binding source property.

For detailed information about data validation, see Data Binding Overview.

For information about how to validate user-provided data in a dialog box, see Dialog Boxes Overview.

The following example shows how to implement a validation rule. The input value is invalid if it contains non-numeric characters or if it is outside the lower and upper bounds. If the value of the returned ValidationResult is invalid, the ErrorContent property is set to the appropriate error message and the IsValid property is set to false.

For the complete example, see How to: Implement Binding Validation.


public class AgeRangeRule : ValidationRule
{
    private int _min;
    private int _max;

    public AgeRangeRule()
    {
    }

    public int Min
    {
        get { return _min; }
        set { _min = value; }
    }

    public int Max
    {
        get { return _max; }
        set { _max = value; }
    }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        int age = 0;

        try
        {
            if (((string)value).Length > 0)
                age = Int32.Parse((String)value);
        }
        catch (Exception e)
        {
            return new ValidationResult(false, "Illegal characters or " + e.Message);
        }

        if ((age < Min) || (age > Max))
        {
            return new ValidationResult(false,
              "Please enter an age in the range: " + Min + " - " + Max + ".");
        }
        else
        {
            return new ValidationResult(true, null);
        }
    }
}


.NET Framework

Supported in: 4, 3.5, 3.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Validation Rule and WPF implementation
$0$0 $0If you are looking for an example of actually implementing this in WPF, this site is missing the WPF part.$0 $0This might help.$0 $0http://www.wpfsharp.com/2012/02/03/how-to-disable-a-button-on-textbox-validationerrors-in-wpf/$0
Example Validation Rule VB.NET
  

Public Class AgeRangeRule
 Inherits ValidationRule
 Private _min As Integer
 Private _max As Integer
 Public Sub New()
 End Sub
 Public Property Min() As Integer
  Get
   Return _min
  End Get
  Set
   _min = value
  End Set
 End Property
 Public Property Max() As Integer
  Get
   Return _max
  End Get
  Set
   _max = value
  End Set
 End Property
 Public Overrides Function Validate(value As Object, cultureInfo As CultureInfo) As ValidationResult
  Dim age As Integer = 0
  Try
   If DirectCast(value, String).Length > 0 Then
    age = Int32.Parse(DirectCast(value, [String]))
   End If
  Catch e As Exception
   Return New ValidationResult(False, "Illegal characters or " + e.Message)
  End Try
  If (age < Min) OrElse (age > Max) Then
   Return New ValidationResult(False, "Please enter an age in the range: " & Min & " - " & Max & ".")
  Else
   Return New ValidationResult(True, Nothing)
  End If
 End Function
End Class