验证具有两组 phone 数字的文本框

Validation for textbox with two sets of phone numbers

我正在尝试对允许在单个文本框中输入一个或多个 phone 数字的文本框进行验证。我想要做的是向文本框中包含的 phone 号码发送消息。 当我在文本框中输入一组数字并且可以发送消息时,我没有问题。 但是,每当我在同一个文本框中输入两组数字时,就会出现验证错误。

我正在使用用户控件并将用户控件放在列表视图中。

这是我的代码:

private ObservableCollection<IFormControl> formFields;
internal ObservableCollection<IFormControl> FormFields
    {
        get
        {
            if (formFields == null)
            {

                formFields = new ObservableCollection<IFormControl>(new List<IFormControl>()
            {
                new TextFieldInputControlViewModel(){ColumnWidth = new GridLength(350) ,HeaderName = "Recipient's mobile number *"  , IsMandatory = true, MatchingPattern = @"^[\+]?[1-9]{1,3}\s?[0-9]{6,11}$", Tag="phone", ContentHeight = 45, ErrorMessage = "Please enter recipient mobile number. "},

            });
            }

            return formFields;
        }
    }

这里是按钮点击事件的代码:

private void OkButton_Click(object sender, RoutedEventArgs e)
    {
        MessageDialog clickMessage;
        UICommand YesBtn;
        int result = 0;

        //Fetch Phone number
        var phoneno = FormFields.FirstOrDefault(x => x.Tag?.ToLower() == "phone").ContentToStore;


        string s = phoneno;
        string[] numbers = s.Split(';');
        foreach (string number in numbers)
        {
            int parsedValue;
            if (int.TryParse(number, out parsedValue) && number.Length.Equals(8))
            {
                result++;
            }
            else
            { }
        }
        if (result.Equals(numbers.Count()))
        {
            try
            {
                for (int i = 0; i < numbers.Count(); i++)
                {
                    Class.SMS sms = new Class.SMS();
                    sms.sendSMS(numbers[i], @"Hi, this is a message from Nanyang Polytechnic School of IT. The meeting venue is located at Block L." + Environment.NewLine + "Click below to view the map " + Environment.NewLine + location);
                    clickMessage = new MessageDialog("The SMS has been sent to the recipient.");
                    timer = new DispatcherTimer();
                    timer.Interval = TimeSpan.FromSeconds(1);
                    timer.Tick += timer_Tick;
                    timer.Start();
                    YesBtn = new UICommand("Ok", delegate (IUICommand command)
                    {
                        timer.Stop();
                        idleTimer.Stop();
                        var rootFrame = (Window.Current.Content as Frame);
                        rootFrame.Navigate(typeof(HomePage));
                        rootFrame.BackStack.Clear();
                    });
                    clickMessage.Commands.Add(YesBtn);
                    clickMessage.ShowAsync();
                }
            }
            catch (Exception ex)
            { }
        }

    }

我试图用 ";" 分隔两个数字sign.....我想知道这是否是问题所在。或者可能是我放入的匹配模式。

答案很简单,在你的 TextFieldInputControlViewModel 中创建一个 bool 属性,比如

public bool AcceptMultiple {get;set;}

为了保持动态,创建一个 char 属性 作为分隔符,如下所示:

public char Separator {get;set;}

现在,通过向新字段添加值来修改您的 new TextFieldInputControlViewModel() 代码语句,如下所示:

new TextFieldInputControlViewModel(){Separator = ';', AcceptMultiple = true, ColumnWidth = new GridLength(350) ,HeaderName = "Recipient's mobile number *"  , IsMandatory = true, MatchingPattern = @"^[\+]?[1-9]{1,3}\s?[0-9]{6,11}$", Tag="phone", ContentHeight = 45, ErrorMessage = "Please enter recipient mobile number. "},

完成后,现在您的 checkValidation() 函数(或您检查验证或模式匹配的地方)可以替换为如下内容:

if(AcceptMultiple)
{
    if(Separator == null)
        throw new ArgumentNullException("You have to provide a separator to accept multiple entries.");

    string[] textItems = textField.Split(Separator);
    if(textItems?.Length < 1)
    {
        ErrorMessage = "Please enter recipient mobile number." //assuming that this is your field for what message has to be shown.
        IsError = true; //assuming this is your bool field that shows all the errors
        return;
    }

    //do a quick check if the pattern matching is mandatory. if it's not, just return.
    if(!IsMandatory)
        return;

    //your Matching Regex Pattern
    Regex rgx = new Regex(MatchingPattern);

    //loop through every item in the array to find the first entry that's invalid
    foreach(var item in textItems)
    {
        //only check for an invalid input as the valid one's won't trigger any thing.
        if(!rgx.IsMatch(item))
        {
            ErrorMessage = $"{item} is an invalid input";
            IsError = true;
            break;  //this statement will prevent the loop from continuing.
        }
    }
}

这样就可以了。

I've taken a few variable names as an assumption as the information was missing in the question. I've mentioned it in the comments about them. Make sure you replace them.