Validation for textbox with two sets of phone numbers

时间:2017-11-13 06:14:54

标签: validation uwp phone-number

I am trying to do a validation on a textbox that can allow the input of one or more phone number in a single textbox. What I am trying to do is to send an message to the phone numbers included in the textbox. I have no problem when I enter just one set of number into the textbox and the message can be sent. However, whenever I type two sets of digit into the same textbox, my validation error will appear.

I am using user controls and putting the user control in a listview.

Here are my codes:

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

And here is the codes for the button click event:

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

    }

I am trying to separate the two numbers with ";" sign.... and I am wondering if that is the problem. Or maybe it is the matchingpattern that I have placed in.

1 个答案:

答案 0 :(得分:1)

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

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

那就行了。

  

我已经采用了一些变量名作为假设,因为问题中缺少信息。我在关于它们的评论中提到过它。确保更换它们。

相关问题