Best practice for parsing and validating mobile number

后端 未结 4 698
说谎
说谎 2020-12-31 17:43

I wonder what the best practice for parsing and validating a mobile number before sending a text is. I\'ve got code that works, but I\'d like to find out better ways of doin

4条回答
  •  无人及你
    2020-12-31 17:52

    Use a regular expression to remove any non-numeric characters instead of trying to guess how a person will enter their number - this will remove all your Replace() and Trim() methods, unless you really need to trim a leading zero.

    string CleanPhone(string phone)
    {
        Regex digitsOnly = new Regex(@"[^\d]");   
        return digitsOnly.Replace(phone, "");
    }
    

    Alternatively, I would recommend you use a masked textbox to collect the # (there are many options available) to allow only numeric input, and display the input with whatever format you'd like. This way you're guaranteeing that the value received will be all numeric characters.

提交回复
热议问题