使用Xamarin.forms中的Entry属性检查以确保第一个输入数字为0



我需要检查用户输入的电话号码,从0开始,长度至少为11。我该怎么做?这是我的代码:

<Entry x:Name="txtPhoneNumber" Placeholder="شماره تلفن" Margin="5,10,10,5" FlowDirection="RightToLeft"
MaxLength="11"
Keyboard="Telephone">
<Entry.Behaviors>
<local:NumericValidationBehavior/>
<local:MaxLengthValidatorBehavior  MaxLength="11"/>
</Entry.Behaviors>
</Entry>

这是NumericValidationBehavior类:

public class NumericValidationBehavior : Behavior<Entry>
{
protected override void OnAttachedTo(Entry entry)
{
entry.TextChanged += OnEntryTextChanged;
base.OnAttachedTo(entry);
}
protected override void OnDetachingFrom(Entry entry)
{
entry.TextChanged -= OnEntryTextChanged;
base.OnDetachingFrom(entry);
}
private static void OnEntryTextChanged(object sender, TextChangedEventArgs args)
{
if (!string.IsNullOrWhiteSpace(args.NewTextValue))
{
bool isValid = args.NewTextValue.ToCharArray().All(x => char.IsDigit(x)); //Make sure all characters are numbers
((Entry)sender).Text = isValid ? args.NewTextValue : args.NewTextValue.Remove(args.NewTextValue.Length - 1);
}
}
}

您可以在中实现的行为中看到代码

<local:NumericValidationBehavior/>
<local:MaxLengthValidatorBehavior  MaxLength="11"/>

如果你分享这两种行为的代码,我可以给你一个更清晰的画面。

请参阅以下代码:-

private static void OnEntryTextChanged(对象发送方,TextChangedEventArgs参数({

if (!string.IsNullOrWhiteSpace(args.NewTextValue))
{
bool isFirstNumberZero = args.NewTextValue.ElementAt(0) == '0';
if(!isFirstNumberZero)
{
((Entry)sender).Text = args.NewTextValue.Remove(args.NewTextValue.Length - 1);
return;
}
bool isValid = args.NewTextValue.ToCharArray().All(x => char.IsDigit(x)); //Make sure all characters are numbers
((Entry)sender).Text = isValid ? args.NewTextValue : args.NewTextValue.Remove(args.NewTextValue.Length - 1);
}
}

有了这个,您可以验证两件事:-1.第一个数字是0。2.所有输入的字符都是数字。

一旦用户点击一些按钮,如完成/提交/登录/下一步。此时,您可以验证输入数字的长度,然后在长度小于11时发出警报。

相关内容

最新更新