简体   繁体   English

在用户输入时验证电话号码的问题,从int转换为大号c#

[英]Issue with Validating Phone number on user input,Int to large c#

Overview of Project: 项目概况:

I am creating a multi form application, which consist of two forms and one parent class. 我正在创建一个多表单应用程序,该应用程序由两种形式和一个父类组成。 Both Forms have a series of validation functions, such as isLetter() isNumber() and isValidEmail() . 两种Forms都有一系列验证功能,例如isLetter() isNumber()isValidEmail() My Issue comes when using the isNumber() Function. 使用isNumber()函数时出现我的问题。

public static bool numValidation(string strNum)
        {
            if (!string.IsNullOrWhiteSpace(strNum))
            {
                int temp;
                if (int.TryParse(strNum, out temp))
                {
                    Console.WriteLine("Phone Number is a valid input: " + temp);
                    return true;
                }
                else
                { Console.WriteLine(temp + "Is not Valid input!!"); }
            }
            return false;
        }

At first glance it works fine but once I tried to break it, I realised that when an actual phone number is entered I get an error saying that the number is too high. 乍看起来,它运作良好,但是一旦我尝试将其断开,我意识到当输入实际电话号码时,我会收到一条错误消息,指出该电话号码太大。 Any ideas how to get round this constraint ? 任何想法如何解决这个约束? as the only reason I need this validation is for phone numbers, Fax etc. I simply need this function to accept very large numbers such as phone numbers 因为我需要此验证的唯一原因是电话号码,传真等。我只需要此功能即可接受非常大的数字,例如电话号码

I suggest that you use a regular expresion to validate the input in your case 我建议您使用常规表达式来验证您的情况下的输入

public static bool numValidation(string strNum)
{

    Regex regex = new Regex(@"^[0-9]+$");

    return (regex.IsMatch(strNum)) ;
}

Parsing a string and not using that value is not really needed. 真正不需要解析字符串而不使用该值。

For more details checkout this answers - Regex for numbers only 有关更多详细信息,请查看此答案- 仅用于数字的正则表达式

From Mauricio Gracia Gutierrez answer 来自毛里西奥·格拉西亚·古铁雷斯答案

I suggest that you use a regular expresion to validate the input in your case 我建议您使用常规表达式来验证您的情况下的输入

public static bool numValidation(string strNum) { 公共静态布尔numValidation(string strNum){

 Regex regex = new Regex(@"^[0-9]+$"); return (regex.IsMatch(strNum)) ; } Parsing a string and not using that value is not really needed. 

For more details checkout this answers - Regex for numbers only 有关更多详细信息,请查看此答案-仅用于数字的正则表达式

You could enhance the expression to check the length of the number: 您可以增强表达式以检查数字的长度:

Between 5 and 10 digits: 5至10位数字:

Regex regex = new Regex(@"^[\d]{5,10}+$");

Max 10 digits: 最多10位数字:

Regex regex = new Regex(@"^[\d]{10}+$");

At least 5 digits: 至少5位数字:

Regex regex = new Regex(@"^[\d]{5,}+$");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM