locked
Validate textbox against a range of float value... RRS feed

  • Question

  • Hi,

    In my application, i want to validate a textbox value for its limit say (0 to 655.34). And also dont want user to enter value more than 655.34 (i.e. 655.35 should give an error to user).

    How i can do this in WPF/XAML?

    Thanks,

    IamHuM

    Thursday, May 16, 2013 7:21 PM

Answers

  • Use a validation rule and set it for the text box.

    This link explains how to do it. You can modify the error template as you wish.

    - Girija

    • Proposed as answer by Thorsten Gudera Thursday, May 16, 2013 11:50 PM
    • Marked as answer by Lisa Zhu Thursday, June 6, 2013 12:15 PM
    Thursday, May 16, 2013 7:49 PM
  • Hi IamHuM,

    Could you please tell us why Girija's suggestion not works for you? I try it my side, it works for me.

    Here is a demo you can refer to:

    .xaml

    <Window  x:Class="WpfApplication1.MainWindow"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfApplication1"      
           Title="MainWindow" 
          Height="200" Width="600" Loaded="Window_Loaded_1">
        <Window.Resources>
            <Style TargetType="{x:Type TextBox}">
                <Style.Triggers>
                    <Trigger Property="Validation.HasError" Value="True">
                        <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},
                            Path=(Validation.Errors)[0].ErrorContent}">   
                        </Setter>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Window.Resources>
    
        <StackPanel>
            <TextBox Name="myTextBox"  >
                <TextBox.Text>
                    <Binding  Path="Text" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>        
                            <local:MyValidationRule Min="0" Max="655.34"/>
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>
       </StackPanel>
    
    </Window>
    

    .cs

    namespace WpfApplication1
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
    
            public MainWindow()
            {
                InitializeComponent();
                this.DataContext = this;      
            }
    
            private string text;
            public string Text
            {
                get { return this.text; }
                set
                {
                   this.text = value;
                   
                }
            }
      }
    
        public class MyValidationRule : ValidationRule
            {
                public double Min { get; set; }
                public double Max { get; set; }
    
                public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
                {
                    ValidationResult vResult = ValidationResult.ValidResult; 
                    double parameter = 0;
                    try
                    {
                      
                        if (((string)value).Length > 0) //Check if there is a input in the textbox
                        {
                            parameter = Double.Parse((String)value);
                        }
                    }
                    catch (Exception e) 
                    { 
                        return new ValidationResult(false, "Illegal characters or " + e.Message); 
                    }
    
                    if ((parameter < this.Min) || (parameter > this.Max))
                     { 
                        return new ValidationResult(false, "Please enter value in the range: " + this.Min + " - " + this.Max + "."); 
                    }
                    return vResult;
                }
    
            }
    }
    Regards,


    Lisa Zhu [MSFT]
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Lisa Zhu Thursday, June 6, 2013 12:15 PM
    Tuesday, June 4, 2013 1:55 PM

All replies

  • Use a validation rule and set it for the text box.

    This link explains how to do it. You can modify the error template as you wish.

    - Girija

    • Proposed as answer by Thorsten Gudera Thursday, May 16, 2013 11:50 PM
    • Marked as answer by Lisa Zhu Thursday, June 6, 2013 12:15 PM
    Thursday, May 16, 2013 7:49 PM
  • Girija,

    Thanks for your reply.

    This is not working for me. Can you please suggest some other solution?

    Thanks,

    IamHuM

    Saturday, May 18, 2013 7:05 AM
  • What is not working. Can you post a sample.

    - Girija

    Monday, May 20, 2013 5:04 AM
  • Hi IamHuM,

    Could you please tell us why Girija's suggestion not works for you? I try it my side, it works for me.

    Here is a demo you can refer to:

    .xaml

    <Window  x:Class="WpfApplication1.MainWindow"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfApplication1"      
           Title="MainWindow" 
          Height="200" Width="600" Loaded="Window_Loaded_1">
        <Window.Resources>
            <Style TargetType="{x:Type TextBox}">
                <Style.Triggers>
                    <Trigger Property="Validation.HasError" Value="True">
                        <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},
                            Path=(Validation.Errors)[0].ErrorContent}">   
                        </Setter>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Window.Resources>
    
        <StackPanel>
            <TextBox Name="myTextBox"  >
                <TextBox.Text>
                    <Binding  Path="Text" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>        
                            <local:MyValidationRule Min="0" Max="655.34"/>
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>
       </StackPanel>
    
    </Window>
    

    .cs

    namespace WpfApplication1
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
    
            public MainWindow()
            {
                InitializeComponent();
                this.DataContext = this;      
            }
    
            private string text;
            public string Text
            {
                get { return this.text; }
                set
                {
                   this.text = value;
                   
                }
            }
      }
    
        public class MyValidationRule : ValidationRule
            {
                public double Min { get; set; }
                public double Max { get; set; }
    
                public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
                {
                    ValidationResult vResult = ValidationResult.ValidResult; 
                    double parameter = 0;
                    try
                    {
                      
                        if (((string)value).Length > 0) //Check if there is a input in the textbox
                        {
                            parameter = Double.Parse((String)value);
                        }
                    }
                    catch (Exception e) 
                    { 
                        return new ValidationResult(false, "Illegal characters or " + e.Message); 
                    }
    
                    if ((parameter < this.Min) || (parameter > this.Max))
                     { 
                        return new ValidationResult(false, "Please enter value in the range: " + this.Min + " - " + this.Max + "."); 
                    }
                    return vResult;
                }
    
            }
    }
    Regards,


    Lisa Zhu [MSFT]
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Lisa Zhu Thursday, June 6, 2013 12:15 PM
    Tuesday, June 4, 2013 1:55 PM