Search code examples
c#parsingxamarinmvvmstring-formatting

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


I have a control of type <Entry> in which I don't want the user to enter values ​​that start with "0", for example...

0

01

00

00010

But if I want to enter values ​​that contain "0" in the form of natural numbers, for example ...

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)));
                }
            }
        }

How can I add this validation once I capture the value of the Entry?

Can I occupy the TryParse Property being a Container Quantity of type string?

Any help for me?


Solution

  • I would create a validation rule.

    In your 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>
    

    Now you crate the validation you see fit. In your case

    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;
        }
    }
    

    And you should be good to go.

    Valid Number Invalid Number