Reputation: 141
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?
Upvotes: 0
Views: 380
Reputation: 656
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.
Upvotes: 1
Reputation: 1666
This one working perfect !!
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;
}
}
Upvotes: 4
Reputation:
You could just cast whatever value you're receiving as a string
.
Then just read the first digit as a substring like so:
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");
}
}
}
Then write in the logic to allow/deny it.
Upvotes: 1