I defined a string data type. Prompted the user to enter 10 numbers. e.g Console.Write("Enter your cell number: "); I want to know how to validate the string and make sure the user entered numbers only
            Asked
            
        
        
            Active
            
        
            Viewed 339 times
        
    1
            
            
        - 
                    How do you as a human decide if something scrawled on a postit is words or numbers? Get the computer to do the same – BugFinder Feb 20 '18 at 10:03
- 
                    1Hint: this is a good place to use regular expressions. But we're not just going to solve the problem for you: you should show what attempt you've made, and what happened. – Jon Skeet Feb 20 '18 at 10:04
- 
                    Try parsing the string.... – FortyTwo Feb 20 '18 at 10:04
- 
                    @un-lucky here is my code for the method im working on. It's not much, I'm completely stuck static bool ValidCharacters(string cellNumber) { int value; bool valid = true; value = } – TheCoder Feb 20 '18 at 10:06
- 
                    You have to define _number_ first. You want to allow any number(like `123456.789`) or only integers? Is this also allowed: `1234567898765432123456789`? – Tim Schmelter Feb 20 '18 at 10:06
- 
                    @TimSchmelter numbers with no decimals, with a max of ten. eg 1234567890 – TheCoder Feb 20 '18 at 10:09
- 
                    max length of 10, min length of 1, only digits: `@"^[\d]{1,10}$"` – Zohar Peled Feb 20 '18 at 10:20
1 Answers
1
            
            
        Best option would be use regular expression to much exactly 10 digits:
Regex pattern = new Regex(@"^\d{10}$");
if(pattern.isMatch(input))
{
    //Do something
    return true;
}
Another option is to use Int64.TryParse, read more here, but that additional checks are needed, to verify that result had 10 digits (no more, no less), number is not negative etc.
 bool result = Int64.TryParse(value, out number);
 if (result)
 {
     Console.WriteLine("Converted '{0}' to {1}.", value, number);             
 }
 
    
    
        Alex
        
- 790
- 7
- 20
- 
                    1
- 
                    3
- 
                    
- 
                    
- 
                    1That would still allow negative numbers - and fewer than or more than 10 digits. If the aim is to check whether a string contains exactly 10 digits, I think a regular expression is the best option. – Jon Skeet Feb 20 '18 at 10:07
- 
                    
- 
                    
- 
                    @Jon Skeet, in this case no, you're right again. It would only help if you will need to find 10 digits number in longer string. I will change answer. – Alex Feb 20 '18 at 10:22
 
    