0

I am having trouble implementing a number validator on a textbox in WPF. If the user enters something like abc into the textbox, an warning/error message should pop up. If they enter in 1.99, that should be fine. What is currently happening, from what I can tell, is that the validation isn't being triggered. The other problem is that on page load, I am setting the value of the textbox to a predefined value but when you see the page loaded, the textbox is empty. So instead of seeing something like 13.42 in the textbox, it's blank. However, when I remove the <TextBox.Text> part, the value appears.

Here's my regex validator class:

public class RegexValidation : ValidationRule
    {
        private string pattern;
        private Regex regex;

        public string Expression
        {
            get { return pattern; }
            set
            {
                pattern = value;
                regex = new Regex(pattern, RegexOptions.IgnoreCase);
            }
        }

        public RegexValidation() { }

        public override ValidationResult Validate(object value, CultureInfo ultureInfo)
        {
            if (value == null || !regex.Match(value.ToString()).Success)
            {
                return new ValidationResult(false, "The value is not a valid number");
            }
            else
            {
                return new ValidationResult(true, null);
            }
        }
    }

Following that, here are my page resources:

<Page.Resources>
        <system:String x:Key="regexDouble">^\d+(\.\d{1,2})?$</system:String>
        <ControlTemplate x:Key="TextBoxErrorTemplate">
            <StackPanel>
                <StackPanel Orientation="Horizontal">                    
                    <AdornedElementPlaceholder x:Name="Holder"/>
                </StackPanel>
                <Label Foreground="Red" Content="{Binding ElementName=Holder, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"/>
            </StackPanel>
        </ControlTemplate>        
    </Page.Resources>  

Lastly, the textbox that requires validation and the button that shouldn't work if a number is not in the textbox:

<TextBox Name="txtItemPrice" Grid.Column="12" Grid.ColumnSpan="2" Grid.Row="4" HorizontalAlignment="Stretch" VerticalAlignment="Center" IsEnabled="False" Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}">
            <TextBox.Text>
                <Binding Path="intPrice" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <classobjects:RegexValidation Expression="{StaticResource regexDouble}"/>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
<Button Name="btnSaveChanges" Content="Save Changes" Grid.Column="4" Grid.Row="11" HorizontalAlignment="Stretch" VerticalAlignment="Center" Visibility="Hidden" Click="btnSaveChanges_Click"/>

Tutorials that I have tried following with no success:

Edit:

I tried something different with how I was trying to set the text. Instead of directly setting the textbox text, I tried to use the binding path property with the following code. However, I am still not having any results.

private string price;
public string intPrice
{
     get { return price; }
     set { price = value; }
}
private void fillInventoryInformation(Inventory i)
{
     //This method is called from the starter method on this page. 
     //Here I am setting the value of intPrice
     intPrice= (Convert.ToDouble(i.intPrice) / 100).ToString();  
     //This was how I was previously trying to set the value of the textbox  
     txtItemPrice.Text = (Convert.ToDouble(i.intPrice) / 100).ToString();    
}
TGills
  • 126
  • 1
  • 2
  • 14
  • hey you should prepare function to validate. Then call it inside the textbox change event. So it will run whenever you typing on that. It will show error message which you define when user type except acceptable characters. – sashiksu Jul 12 '18 at 17:04
  • If you have time, could you please provide a link on how to do that? – TGills Jul 12 '18 at 17:07
  • [This](https://stackoverflow.com/questions/463299/how-do-i-make-a-textbox-that-only-accepts-numbers) thread will help you. – sashiksu Jul 12 '18 at 17:09
  • I'll look into it. Thank you – TGills Jul 12 '18 at 17:11
  • Instead of using `!regex.Match(value.ToString()).Success` try `!regex.IsMatch(value.ToString())` It was designed for validation. – emsimpson92 Jul 12 '18 at 18:05
  • It might work, but I don't think it is triggering. I have break points inside of the validator itself, and they are not being triggered – TGills Jul 12 '18 at 18:13
  • @TGills: What's the type of the `intPrice` source property that you bind to? – mm8 Jul 13 '18 at 12:01
  • @mm8 I'm currently trying to figure out what binding path does. I am manually setting it from a different method that is triggered when it loads. However, I had thought that instead of doing that, I could go public string intPrice {get; set;} and assign that a value which would be read from the binding – TGills Jul 13 '18 at 16:24

1 Answers1

0

Fixed my issue, and the validator works as intended. The issue was with how I was binding. I was trying to set the text of each textbox in the code behind and not using the binding path. Once I switched from going txtTextbox.Text = "123" to the following, everything fell into place and started working properly.

private void fillInventoryInformation(Inventory i)
{
    DataContext = i;
}
TGills
  • 126
  • 1
  • 2
  • 14