【问题标题】:Validation for textbox with two sets of phone numbers使用两组电话号码验证文本框
【发布时间】:2018-04-25 18:26:55
【问题描述】:

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

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

这是我的代码:

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

    }

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

【问题讨论】:

    标签: validation uwp phone-number


    【解决方案1】:

    答案很简单,在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.
            }
        }
    }
    

    这样就可以了。

    我假设了一些变量名称,因为问题中缺少信息。我在关于他们的 cmets 中提到过。确保更换它们。

    【讨论】:

    • 我是在xaml.cs下添加代码还是在视图模型下添加代码?
    • 顺便说一句...我想允许输入一组或多组数字...所以我必须更改上面给出的if语句对吗?
    • new TextFieldInputControlViewModel() 进入xaml.cs,而方法进入TextFieldInputControlViewModel
    猜你喜欢
    • 2014-11-30
    • 2019-02-28
    • 2021-05-22
    • 2011-05-19
    • 2013-08-24
    • 1970-01-01
    相关资源
    最近更新 更多