C#中如何验证输入的数字不带“0”

How to validate that the entry of a number is not with "0" in C #

我有一个<Entry>类型的控件,我不希望用户输入以“0”开头的值,例如...

0

01

00

00010

但是如果我想以自然数的形式输入包含“0”的值,例如...

10

2010

200000

MyView.XAML:

<Entry
      HorizontalOptions="FillAndExpand"
      Placeholder="Cantidad"
      Keyboard="Numeric"
      MaxLength="9"
      Text="{Binding CantidadContenedor}"></Entry>

MyViewModel.CS:

   string cantidadContenedor;

   public string CantidadContenedor
        {
            get
            {
                return  cantidadContenedor;
            }
            set
            {
                if (cantidadContenedor != value)
                {
                    cantidadContenedor = value;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CantidadContenedor)));
                }
            }
        }

捕获 Entry 的值后如何添加此验证?

作为 string 类型的 Container Quantity 我可以占用 TryParse 属性 吗?

对我有什么帮助吗?

您可以将收到的任何值转换为 string

然后像这样读取第一个数字作为子字符串:

using System;

public class Program
{
    public static void Main()
    {
        string x = "0TEST";
        if(x.StartsWith("0")){
            Console.WriteLine("Starts with 0");
        }else{
            Console.WriteLine("Doesn't start with 0");
        }
    }
}

然后把逻辑写到allow/deny里面去。

这个工作完美!!

    public MainPage()
    {
        InitializeComponent();

        MyEntry.TextChanged+= MyEntry_TextChanged;
    }

    void MyEntry_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e)
    {
        if(!string.IsNullOrWhiteSpace(MyEntry.Text))
        {
            if (MyEntry.Text.StartsWith("0"))
                MyEntry.Text = e.OldTextValue;
        }
    }

我会创建一个验证规则。

在你的XAML

<Entry
  HorizontalOptions="FillAndExpand"
  Placeholder="Cantidad"
  Keyboard="Numeric"
  MaxLength="9">
  <Entry.Text>
     <Binding Path=CantidadContenedor>
         <Binding.ValidationRules>
             <validationRules:StartWithRule Prefix="0"/>
     </Binding>
  </Entry.Text>
</Entry>

现在您创建您认为合适的验证。你的情况

public class StartWithRule : ValidationRule
{
    public string Prefix { get; set; }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        // Pass the value to string
        var numberToCheck = (string) value;

        if (numberToCheck == null) return ValidationResult.ValidResult;

        // Check if it starts with prefix
        return numberToCheck.StartsWith(Prefix)
            ? new ValidationResult(false, $"Starts with {Prefix}")
            : ValidationResult.ValidResult;
    }
}

你应该可以开始了。