文本框验证

  1. ValidationRules
<--文本框验证
         引用资源
  xmlns:XX="clr-namespace:XX;assembly=XX"
 <TextBox>
     <TextBox.Text>
         <Binding Path="Config.Id" Mode="TwoWay" UpdateSourceTrigger="LostFocus" >
             <Binding.ValidationRules>
                 <ExceptionValidationRule/>
                 <XX:InputValidationRule Type="NotEmpty"/>
                 <XX:InputValidationRule Type="NetID"/>
             </Binding.ValidationRules>
         </Binding>
     </TextBox.Text>
 </TextBox>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO.Packaging;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Xml;

namespace XX
{/// <summary>
/// 
/// </summary>
    public class InputValidationRule : ValidationRule 
    {
    
        public ValidationTypeEnum Type { get; set; }
        public int MaxLength { get; set; }



        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            string input = value as string;

            switch (Type)
            {
                case ValidationTypeEnum.PositiveInteger:
                    if (!ValidationType.IsPositiveInteger(input))
                        return new ValidationResult(false, "必须为正整数");
                    else
                        return new ValidationResult(true, null);

                case ValidationTypeEnum.StringLength:
                    if (!ValidationType.IsStringLengthValid(input, MaxLength))
                        return new ValidationResult(false, $"最大长度 {MaxLength} 个字符");
                    else
                        return new ValidationResult(true, null);

                case ValidationTypeEnum.NoIllegalCharacters:
                    if (ValidationType.ContainsIllegalCharacters(input))
                        return new ValidationResult(false, "包含非法字符!\\ / : * ? \" < > |");
                    else
                        return new ValidationResult(true, null);

                case ValidationTypeEnum.NotEmpty:
                    if (!ValidationType.IsNotEmpty(input))
                        return new ValidationResult(false, "不能为空");
                    else
                        return new ValidationResult(true, null);
                case ValidationTypeEnum.NetID:
                    if (!ValidationType.IsNetIDValid(input))
                        return new ValidationResult(false, "NetID格式不正确,正确格式如:192.168.1.40.1.1");
                    else
                        return new ValidationResult(true, null);
                   
                case ValidationTypeEnum.PidPort:
                    if (!ValidationType.IsPortID(input))
                        return new ValidationResult(false, "端口格式不正确,端口范围为0-65535");
                    else
                        return new ValidationResult(true, null);

                default:
                    throw new ArgumentOutOfRangeException();
            }

            return ValidationResult.ValidResult;
        }
    }

    public static class ValidationType
    {
        public static char[] IllegalCharacters = { '\\', '/', ':', '*', '?', '"', '<', '>', '|' };
        public static bool IsPositiveInteger(string input)
        {
            int value;
            return int.TryParse(input, out value) && value > 0;
        }

        public static bool IsStringLengthValid(string input, int maxLength)
        {
            return !string.IsNullOrEmpty(input) && input.Length <= maxLength;
        }

        public static bool ContainsIllegalCharacters(string input)
        {
            return !string.IsNullOrEmpty(input) && input.Any(c => IllegalCharacters.Contains(c));
        }

        public static bool IsNotEmpty(string input)
        {
            return !string.IsNullOrEmpty(input);
        }
        public static bool IsNetIDValid(string input)
        {
            // 实现逻辑,判断是否是合法的 netid 格式
            string[] segments = input.Split('.');

            // netid 格式要求:共有 6 段,每段为正整数
            if (segments.Length == 6)
            {
                foreach (var segment in segments)
                {
                    int value;
                    if (!int.TryParse(segment, out value) || value < 0)
                    {
                        return false;
                    }
                }
                return true;
            }

            return false;
        }
        public static bool IsPortID(string input)
        {
            // 实现逻辑,判断是否是合法的端口号
            int port;
            return int.TryParse(input, out port) && port >= 0 && port <= 65535;
        }
        public static bool IsIpAddress(string input)
        {
            IPAddress iPAddress;
            return IPAddress.TryParse(input, out iPAddress);
        }

    }

    public enum ValidationTypeEnum
    {
        PositiveInteger,
        StringLength,
        NoIllegalCharacters,
        NotEmpty,
        NetID,
        IP,
        PidPort,
        IpAddress
    }
}

2.直接设置禁用输入法,并添加PreviewTextInput事件,如果不满足条件,就禁止输入

<TextBox InputMethod.IsInputMethodEnabled="True" PreviewTextInput="TextBox_PreviewTextInput" Margin="10"/>
using System.Text.RegularExpressions;
using System.Windows;

namespace wpfcore
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;

        }
        private void TextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            e.Handled = new Regex("[^0-9]+").IsMatch(e.Text);
        }
    }

}

3.附加属性

<TextBox local:TextBoxAttachedProperties.IsOnlyNumber="true" Margin="10"/>
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace wpfcore
{
    public class TextBoxAttachedProperties
    {
        public static bool GetIsOnlyNumber(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsOnlyNumberProperty);
        }
        public static void SetIsOnlyNumber(DependencyObject obj, bool value)
        {
            obj.SetValue(IsOnlyNumberProperty, value);
        }
        public static readonly DependencyProperty IsOnlyNumberProperty =
            DependencyProperty.RegisterAttached("IsOnlyNumber", typeof(bool), typeof(TextBox), new PropertyMetadata(false,
                (s, e) =>
                {
                    if (s is TextBox textBox)
                    {
                        textBox.SetValue(InputMethod.IsInputMethodEnabledProperty, !(bool)e.NewValue);
                        textBox.PreviewTextInput -= TxtInput;
                        if (!(bool)e.NewValue)
                        {
                            textBox.PreviewTextInput += TxtInput;
                        }
                    }
                }));
        private static void TxtInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            e.Handled = new Regex("[^0-9]+").IsMatch(e.Text);
        }
    }
}