How to validate textbox with empty field in wpf forms

Gcobani Mkontwana 40 Reputation points
2024-04-24T11:21:49.9533333+00:00

Hi Team

I have these two fields i want to validate, does anyone knows how to achieve this in wpf on the forms? The bottom seal and TopSeal fields, if empty it must prompt a window dialog message.

User's image

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,854 questions
0 comments No comments
{count} votes

Accepted answer
  1. Hui Liu-MSFT 41,146 Reputation points Microsoft Vendor
    2024-04-25T03:01:02.3233333+00:00

    Hi,@Gcobani Mkontwana. Welcome to Microsoft Q&A.

    To show the error message in the TextBox itself and display a dialog window when validation fails, you can modify the EmptyRule class to store the error message and handle it in the view model.

      <Window.DataContext>
          <local:ViewModel/>
      </Window.DataContext>
      <StackPanel>
          <Label  Width="200" Content="Bottom Seal:"/>
          <TextBox Name="tb"      local:FocusHelper.ShouldFocus="{Binding ShouldFocusBottomSeal}"
                   Width="200" Text="{Binding BottomSeal, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"  >
              <Validation.ErrorTemplate>
                  <ControlTemplate>
                      <DockPanel>
                          <Border BorderBrush="Red" BorderThickness="1">
                              <AdornedElementPlaceholder x:Name="textBox"/>
                          </Border>
                          <TextBlock Text="{Binding [0].ErrorContent}" Foreground="Red"/>
                      </DockPanel>
                  </ControlTemplate>
              </Validation.ErrorTemplate>
          </TextBox>
    
      </StackPanel>
    
    

    Codebehind:

        public class ViewModel : INotifyPropertyChanged, IDataErrorInfo
        {
            public ViewModel()
            {
                ValidateBottomSeal();
            }
            private string _bottomSeal;
            public string BottomSeal
            {
                get { return _bottomSeal; }
                set
                {
                    _bottomSeal = value;
                    ValidateBottomSeal();
                    RaisePropertyChanged(nameof(BottomSeal));
                }
            }
            private bool _shouldFocusBottomSeal;
            public bool ShouldFocusBottomSeal
            {
                get { return _shouldFocusBottomSeal; }
                set
                {
                    _shouldFocusBottomSeal = value;
                    RaisePropertyChanged(nameof(ShouldFocusBottomSeal));
                }
            }
            private EmptyRule _emptyRule = new EmptyRule();
            private void ValidateBottomSeal()
            {
                var result = _emptyRule.Validate(BottomSeal, CultureInfo.CurrentCulture);
                if (!result.IsValid)
                {
                    MessageBox.Show(result.ErrorContent.ToString(), "Validation Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    ShouldFocusBottomSeal = true;
                }
            }
            public string Error => null;
            public string this[string columnName]
            {
                get
                {
                    if (columnName == nameof(BottomSeal) && string.IsNullOrEmpty(BottomSeal))
                    {
                        return "Bottom Seal is required!";
                    }
                    return null;
                }
            }
            public event PropertyChangedEventHandler PropertyChanged;
    
            protected virtual void RaisePropertyChanged(string propertyName)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        public class EmptyRule : ValidationRule
        {
            public string ErrorMessage { get; set; }
    
            public override ValidationResult Validate(object value, CultureInfo cultureInfo)
            {
                if (string.IsNullOrWhiteSpace(value as string))
                {
                    ErrorMessage = "Field cannot be empty.";
                    return new ValidationResult(false, ErrorMessage);
                }
                else
                {
                    ErrorMessage = null;
                    return ValidationResult.ValidResult;
                }
            }
        }
        public static class FocusHelper
        {
            public static readonly DependencyProperty ShouldFocusProperty =
                DependencyProperty.RegisterAttached("ShouldFocus", typeof(bool), typeof(FocusHelper), new PropertyMetadata(false, OnShouldFocusChanged));
    
            public static bool GetShouldFocus(DependencyObject obj)
            {
                return (bool)obj.GetValue(ShouldFocusProperty);
            }
    
            public static void SetShouldFocus(DependencyObject obj, bool value)
            {
                obj.SetValue(ShouldFocusProperty, value);
            }
    
            private static void OnShouldFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                if (d is FrameworkElement element && (bool)e.NewValue)
                {
                    element.Focus();
                    SetShouldFocus(element, false); // Reset the attached property
                }
            }
        }
    

    The result:

    When the property is empty, the MessageBox will display "Field cannot be empty."; and the error message "Bottom Seal is required!" will appear near the TextBox.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful