Click here to Skip to main content
13,295,192 members (69,322 online)
Click here to Skip to main content


258 bookmarked
Posted 19 Aug 2006

Validation in Windows Presentation Foundation

, 19 Aug 2006
In this article, I'll walk you through using the built-in Validation classes that exist in Windows Presentation Foundation. I'll then discuss an alternative approach to validation that might suit a richer domain layer, by creating a custom WPF ErrorProvider.
using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.Windows.Controls;

namespace PaulStovell.Samples.WpfValidation
    public class StringRangeValidationRule : ValidationRule
        private int _minimumLength = -1;
        private int _maximumLength = -1;
        private string _errorMessage;

        public int MinimumLength
            get { return _minimumLength; }
            set { _minimumLength = value; }

        public int MaximumLength
            get { return _maximumLength; }
            set { _maximumLength = value; }

        public string ErrorMessage
            get { return _errorMessage; }
            set { _errorMessage = value; }

        public override ValidationResult Validate(object value,
            CultureInfo cultureInfo)
            ValidationResult result = new ValidationResult(true, null);
            string inputString = (value ?? string.Empty).ToString();
            if (inputString == null)
                inputString = string.Empty;

            if (inputString.Length < this.MinimumLength ||
                   (this.MaximumLength > 0 &&
                    inputString.Length > this.MaximumLength))
                result = new ValidationResult(false, this.ErrorMessage);
            return result;

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Paul Stovell
Octopus Deploy
Australia Australia
My name is Paul Stovell. I live in Brisbane and develop an automated release management product, Octopus Deploy. Prior to working on Octopus I worked for an investment bank in London, and for Readify. I also work on a few open source projects. I am a Microsoft MVP for Client Application Development.

You may also be interested in...

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171207.1 | Last Updated 20 Aug 2006
Article Copyright 2006 by Paul Stovell
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid