Issue
I have an <Entry>
control where the user is allowed to enter decimal numbers, for examenple ...
0,2
0,02
5,405
But I do not want to enter a "0" (as a decimal), as follows
0,0
0,00
00,00
The control used in my Vista is an
MyView.XAML:
<Entry
HorizontalOptions="FillAndExpand"
Placeholder="Cantidad"
Keyboard="Numeric"
MaxLength="5"
Text="{Binding CantidadEstimado}"></Entry>
To then capture the value with a string type in the following way in my ViewModel
ViewModel.CS:
string cantidadEstimado;
public string CantidadEstimado
{
get
{
return cantidadEstimado;
}
set
{
if (cantidadEstimado != value)
{
cantidadEstimado = value.setOnlyNumbersDouble();
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CantidadEstimado)));
}
}
}
As seen in my Property Amount Dear I have the call to the method setOnlyNumberDouble (), which gives the user the possibility to enter a single comma (","), I attach the following method ...
public static string setOnlyNumbersDouble(this string s)
{
string sTemp = "";
foreach (var item in s)
{
if (item == ',')
{
if (!sTemp.Contains(","))
{
sTemp += item;
}
}
else
{
sTemp += item;
}
}
return Regex.Replace(sTemp, @"[^0-9,]+", "");
}
How can I validate that the user does not enter a "0" as a decimal? Can I reuse my setOnlyNumberDouble () method? any help for me?
Solution
You may use RegularExpressions:
bool isZero = Regex.Matches(input,"[0,]");
Or
bool isZero = int.Parse(input.Replace(",","") == 0;
Instead of trying to forcing it to be a valid double number by removing extra commas, non-numeric chars ,... try to validate it:
public static bool IsValidDouble(this string s)
{
double d = 0;
double.TryParse(s, out d);
return d != 0; //will be false if result is 0
//return d > 0; if you don't want negativer values
}
Answered By - Ashkan Mobayen Khiabani Answer Checked By - Robin (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.