Anil Sharma

just for code

TextBox Validation in WPF

To validate textinput type in wpf  is good by introduce dependency property.

Now we have many types of validation

1-Numeric

2-AlphaNumeric

3-Decimal

To support all types of validation we have Enum type

public enum TextValidationType
{
/// <summary>
/// Default Value
/// </summary>
Default = 0,

/// <summary>
/// For Numeric value validation
/// </summary>
Numeric = 1,

/// <summary>
///  For Deciaml value validation
/// </summary>
Decimal = 2,

/// <summary>
///  For Alphanumeric value validation
/// </summary>
Alphanumeric = 3,

/// <summary>
///  For Letter validation
/// </summary>
Letter = 4,

/// <summary>
///  For LetterUppercase value validation
/// </summary>
LetterUppercase = 5,

/// <summary>
///  For LetterLowercase value validation
/// </summary>
LetterLowercase = 6,

/// <summary>
///  For Numeric with dash value validation
/// </summary>
NumericSSN = 7,

/// <summary>
///  For Numenric with dash value validation
/// </summary>
NumericVital = 8,

/// <summary>
///  For AlphaNumericVital with dash value validation
/// </summary>
AlphaNumericVital = 9,

/// <summary>
///  For NegativeDecimal with dash value validation
/// </summary>
NegativeDecimal = 10,

/// <summary>
/// For Numeric Value with Percentage validation
/// </summary>
NumericPercent = 11,

/// <summary>
/// For Numeric Value with Zip validation
/// </summary>
NumericZip=12

}

And Class Is

————————————

public static class TextBoxValidation
{
static int intCaretIndex = 0;
static int inttextboxlength=0;

#region Focus Change

/// <summary>
/// Gets the focus change.
/// </summary>
/// <param name=”obj”>The obj.</param>
/// <returns></returns>
public static bool GetFocusChange(DependencyObject obj)
{
return (bool)obj.GetValue(FocusChangeProperty);
}

/// <summary>
/// Sets the focus change.
/// </summary>
/// <param name=”obj”>The obj.</param>
/// <param name=”value”>if set to <c>true</c> [value].</param>
public static void SetFocusChange(DependencyObject obj, bool value)
{
obj.SetValue(FocusChangeProperty, value);
}

// Using a DependencyProperty as the backing store for MaxValue.  This enables animation, styling, binding, etc…
/// <summary>
/// MAx Value Dependency Property
/// </summary>
public static readonly DependencyProperty FocusChangeProperty =
DependencyProperty.RegisterAttached(“FocusChange”, typeof(bool), typeof(TextBoxValidation), new UIPropertyMetadata(null));

#endregion

#region MAXVALUE
/// <summary>
/// Gets the max value.
/// </summary>
/// <param name=”obj”>The obj.</param>
/// <returns></returns>
public static decimal GetMaxValue(DependencyObject obj)
{
return (decimal)obj.GetValue(MaxValueProperty);
}

/// <summary>
/// Sets the max value.
/// </summary>
/// <param name=”obj”>The obj.</param>
/// <param name=”value”>The value.</param>
public static void SetMaxValue(DependencyObject obj, decimal value)
{
obj.SetValue(MaxValueProperty, value);
}

// Using a DependencyProperty as the backing store for MaxValue.  This enables animation, styling, binding, etc…
/// <summary>
/// MAx Value Dependency Property
/// </summary>
public static readonly DependencyProperty MaxValueProperty =
DependencyProperty.RegisterAttached(“MaxValue”, typeof(decimal), typeof(TextBoxValidation), new UIPropertyMetadata(null));
#endregion

#region MinValue
/// <summary>
/// Gets the Min value.
/// </summary>
/// <param name=”obj”>The obj.</param>
/// <returns></returns>
public static decimal GetMinValue(DependencyObject obj)
{
return (decimal)obj.GetValue(MinValueProperty);
}

/// <summary>
/// Sets the Min value.
/// </summary>
/// <param name=”obj”>The obj.</param>
/// <param name=”value”>The value.</param>
public static void SetMinValue(DependencyObject obj, decimal value)
{
obj.SetValue(MinValueProperty, value);
}

// Using a DependencyProperty as the backing store for MaxValue.  This enables animation, styling, binding, etc…
/// <summary>
/// MAx Value Dependency Property
/// </summary>
public static readonly DependencyProperty MinValueProperty =
DependencyProperty.RegisterAttached(“MinValue”, typeof(decimal), typeof(TextBoxValidation), new UIPropertyMetadata(null));

#endregion

/// <summary>
/// Gets the type of the text box validation.
/// </summary>
/// <param name=”obj”>The obj.</param>
/// <returns></returns>
public static TextValidationType GetTextBoxValidationType(DependencyObject obj)
{
return (TextValidationType)obj.GetValue(TextBoxValidationTypeProperty);
}

/// <summary>
/// Sets the type of the text box validation.
/// </summary>
/// <param name=”obj”>The obj.</param>
/// <param name=”value”>The value.</param>
public static void SetTextBoxValidationType(DependencyObject obj, TextValidationType value)
{
obj.SetValue(TextBoxValidationTypeProperty, value);
}

// Using a DependencyProperty as the backing store for TextBoxValidationType.  This enables animation, styling, binding, etc…
public static readonly DependencyProperty TextBoxValidationTypeProperty =
DependencyProperty.RegisterAttached(“TextBoxValidationType”, typeof(TextValidationType), typeof(TextBoxValidation), new UIPropertyMetadata(TextValidationType.Default, OnValueChanged));

/// <summary>
/// Handles changes to the IsDecimalOnly property.
/// </summary>
/// <param name=”d”><see cref=”DependencyObject”/> that fired the event</param>
/// <param name=”e”>A <see cref=”DependencyPropertyChangedEventArgs”/> that contains the event data.</param>
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextValidationType isNumeric = (TextValidationType)e.NewValue;
if (d.DependencyObjectType.Name == “TextBox”)
{
TextBox textBox = (TextBox)d;

if (isNumeric != TextValidationType.Default)
{
textBox.PreviewTextInput += BlockNonDigitCharacters;
textBox.TextChanged += TextBox_TextChanged;
textBox.PreviewKeyDown += ReviewKeyDown;
}
else
{
textBox.PreviewTextInput -= BlockNonDigitCharacters;
textBox.PreviewKeyDown -= ReviewKeyDown;
textBox.TextChanged -= TextBox_TextChanged;
}
}
}

/// <summary>
/// Handles the TextChanged event of the textBox control.
/// </summary>
/// <param name=”sender”>The source of the event.</param>
/// <param name=”e”>The <see cref=”System.Windows.Controls.TextChangedEventArgs”/> instance containing the event data.</param>
public static void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
DependencyObject depSender = sender as DependencyObject;

TextBox textBox = (sender as TextBox);
decimal value, maxValue, minvalue;
decimal.TryParse(textBox.Text, out value);
maxValue = GetMaxValue(depSender);
minvalue = GetMinValue(depSender);
int intMin = ((System.Windows.Controls.TextBox)(((System.Windows.RoutedEventArgs)(e)).Source)).CaretIndex – 1;
TextValidationType isNumeric = GetTextBoxValidationType((DependencyObject)sender);
if (isNumeric != TextValidationType.NumericPercent)
{
if (maxValue != 0 || minvalue != 0)
{
CalculateMaxLength(e, textBox, intMin, value, maxValue, minvalue);
return;
}
}
else
{
if (value < maxValue && value > minvalue && intMin < textBox.MaxLength)
{
e.Handled = true;
return;

}
if (intMin == textBox.MaxLength – 1)
{

textBox.Text = textBox.Text.Remove(textBox.Text.Length – 1);
textBox.Text = textBox.Text.Insert(intMin, “%”);
textBox.CaretIndex = textBox.Text.Length;
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;

}
if (intMin == 0 && textBox.Text.Contains(“%”))
{
textBox.Text = textBox.Text.Remove(textBox.Text.Length – 1);
textBox.CaretIndex = textBox.Text.Length;
e.Handled = true;
return;
}
}

}

/// <summary>
/// Calculates the length of the max.
/// </summary>
/// <param name=”e”>The <see cref=”System.Windows.Controls.TextChangedEventArgs”/> instance containing the event data.</param>
/// <param name=”textBox”>The text box.</param>
/// <param name=”intMin”>The int min.</param>
/// <param name=”value”>The value.</param>
/// <param name=”maxValue”>The max value.</param>
/// <param name=”minvalue”>The minvalue.</param>
private static void CalculateMaxLength(TextChangedEventArgs e, TextBox textBox, int intMin, decimal value, decimal maxValue, decimal minvalue)
{
if (string.IsNullOrEmpty(textBox.Text))
{
textBox.MaxLength = inttextboxlength;
return;
}
if (value <= maxValue && value >= minvalue)
{
e.Handled = true;
return;
}
else if (value > maxValue || value < minvalue)
{
EndofTextboxFocusChange(e, textBox);
return;
}

}

/// <summary>
/// Focuses the navigation direction for textbox.
/// </summary>
private static void FocusNavigationDirectionForTextbox()
{
FocusNavigationDirection focusDirection = FocusNavigationDirection.Next;

// MoveFocus takes a TraveralReqest as its argument.
TraversalRequest request = new TraversalRequest(focusDirection);

// Gets the element with keyboard focus.
UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;

// Change keyboard focus.
if (elementWithFocus != null)
{
elementWithFocus.MoveFocus(request);
}
}

/// <summary>
/// Endofs the textbox focus change.
/// </summary>
/// <param name=”e”>The <see cref=”System.Windows.Controls.TextChangedEventArgs”/> instance containing the event data.</param>
/// <param name=”textBox”>The text box.</param>
private static void EndofTextboxFocusChange(TextChangedEventArgs e, TextBox textBox)
{
textBox.Text = textBox.Text.Remove(textBox.Text.Length – 1);
textBox.CaretIndex = textBox.Text.Length;
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;
}

/// <summary>
/// Disallows non-digit character.
/// </summary>
/// <param name=”sender”>The source of the event.</param>
/// <param name=”e”>An <see cref=”TextCompositionEventArgs”/> that contains the event data.</param>
private static void BlockNonDigitCharacters(object sender, TextCompositionEventArgs e)
{
TextBox textBox = (sender as TextBox);
int objSender = textBox.CaretIndex;
TextValidationType isNumeric = GetTextBoxValidationType((DependencyObject)sender);
foreach (char ch in e.Text)
{
if ((string.IsNullOrEmpty(textBox.Text) && textBox.MaxLength == inttextboxlength) ||
inttextboxlength==0)
{
inttextboxlength = textBox.MaxLength;
}
if (isNumeric == TextValidationType.Numeric)
{
if (!Char.IsDigit(ch))
{
e.Handled = true;
}
if (objSender == textBox.MaxLength – 1)
{
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;
}
}
else if (isNumeric == TextValidationType.Decimal)
{

if (!Char.IsDigit(ch) && ch != ‘.’)
{
e.Handled = true;
}
if (textBox.Text.Contains(“.”) && ch == ‘.’)
{
e.Handled = true;
}
if (ch == ‘.’ && !textBox.Text.Contains(“.”))
{
textBox.MaxLength = inttextboxlength;
textBox.MaxLength = textBox.MaxLength + 3;
}
if (objSender == textBox.MaxLength)
{
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;
}
}
else if (isNumeric == TextValidationType.Alphanumeric)
{
if (!char.IsLetterOrDigit(ch) && ch != ‘.’)
{
e.Handled = true;
}
if (textBox.Text.Contains(“.”) && ch == ‘.’)
{
e.Handled = true;
}
if (objSender == textBox.MaxLength – 1)
{
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;
}
}
else if (isNumeric == TextValidationType.Letter)
{
if (!char.IsLetter(ch))
{
e.Handled = true;
}
}
else if (isNumeric == TextValidationType.LetterLowercase)
{
if (!char.IsLetter(ch) || !char.IsLower(ch))
{
e.Handled = true;
}
}
else if (isNumeric == TextValidationType.LetterUppercase)
{
if (!char.IsLetter(ch) || !char.IsUpper(ch))
{
e.Handled = true;
}
}
else if (isNumeric == TextValidationType.NumericSSN)
{
if (objSender == 3 || objSender == 6)
{
if (!char.IsDigit(ch) && ch == ‘-‘)
{
e.Handled = false;
}
else
{
e.Handled = true;
}

}
else if (!char.IsDigit(ch))
{
e.Handled = true;
}

}
else if (isNumeric == TextValidationType.NumericVital)
{
if ((!Char.IsDigit(ch) && ch != ‘-‘) ||
(textBox.Text.Contains(“-“) && ch == ‘-‘) ||
(objSender != 0 && ch == ‘-‘))
{
e.Handled = true;
}
if (ch == ‘-‘)
{
textBox.MaxLength = textBox.MaxLength + 1;
}
if (objSender == textBox.MaxLength)
{
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;
}
}
else if (isNumeric == TextValidationType.AlphaNumericVital)
{
if (!char.IsLetterOrDigit(ch) && ch == ‘-‘)
{
e.Handled = false;
}
if ((textBox.Text.Contains(“-“) && ch == ‘-‘) ||
(objSender != 0 && ch == ‘-‘))
{
e.Handled = true;
}
if (ch == ‘-‘)
{
textBox.MaxLength = textBox.MaxLength + 1;
}
if (objSender == textBox.MaxLength)
{
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;
}
}
else if (isNumeric == TextValidationType.NegativeDecimal)
{

if (!Char.IsDigit(ch) && ch != ‘.’ && ch != ‘-‘)
{
e.Handled = true;
}
if ((textBox.Text.Contains(“.”) && ch == ‘.’) ||
(objSender != 0 && ch == ‘-‘))
{
e.Handled = true;
}
if (ch == ‘-‘)
{
textBox.MaxLength = textBox.MaxLength + 1;
}
if (ch == ‘.’ && !textBox.Text.Contains(“.”))
{
textBox.MaxLength = inttextboxlength;
textBox.MaxLength = textBox.MaxLength + 3;
}
if (objSender == textBox.MaxLength)
{
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;
}

}
else if (isNumeric == TextValidationType.NumericPercent)
{
if (!Char.IsDigit(ch) && ch != ‘%’)
{
e.Handled = true;
}
if (textBox.Text.Contains(“%”) && ch == ‘%’)
{
e.Handled = true;
}
if (textBox.Text.Contains(“%”))
{
intCaretIndex = textBox.Text.IndexOf(‘%’);
if (intCaretIndex < objSender)
e.Handled = true;
}
if (objSender == textBox.MaxLength – 1)
{
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;
}
}
else if (isNumeric == TextValidationType.NumericZip)
{
if (objSender == 2 || objSender == 5 || objSender == 8)
{
if (!char.IsDigit(ch) && ch == ‘-‘)
{
e.Handled = false;
}
else
{
e.Handled = true;
}

}
else if (!char.IsDigit(ch))
{
e.Handled = true;
}
}
}
}

/// <summary>
/// space key.
/// </summary>
/// <param name=”sender”>The source of the event.</param>
/// <param name=”e”>An <see cref=”KeyEventArgs”/> that contains the event data.</param>
private static void ReviewKeyDown(object sender, KeyEventArgs e)
{
TextValidationType isNumeric = GetTextBoxValidationType(sender as DependencyObject);
if (e.Key == Key.Space)
{
if (isNumeric == TextValidationType.Alphanumeric)
{
// Allow the space key, which  raises a PreviewTextInput event.
e.Handled = false;
}
else
{
// Disallow the space key, which doesn’t raise a PreviewTextInput event.
e.Handled = true;
}
}
}
}

———————————————–

USE IN xaml

MAKE REFERENCE IN XAML

xmlns:UC=”clr-namespace:Test.Presentation.UserControls” /// Location of TextValidation file

<TextBox Grid.Row=”4″ Grid.Column=”1″
UC:TextBoxValidation.TextBoxValidationType=”NumericZip”/>

March 23, 2011 Posted by | TextBox Validation, WPF | , , , , , , , , | Leave a comment