本文純乾貨,直接拿走使用,不用付費。在業務開發中,手機號碼驗證是咱們經常須要面對的問題,目前市場上各類各樣的手機號碼驗證方式,好比正則表達式等等,本文結合實際業務場景,在業務級別對手機號碼進行嚴格驗證;同時增長可配置方式,方便業務擴展,代碼很是簡單,擴展很是靈活。git
"中國電信": "133,153,189,180,181,177,173,199,174,141", "中國移動": "139,138,137,136,135,134,159,158,157,150,151,152,147,188,187,182,183,184,178,198", "中國聯通": "130,131,132,146,156,155,166,186,185,145,175,176", "虛擬運營商": "170,171", "內部號碼": "123"
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "phone-segment": { "中國電信": "133,153,189,180,181,177,173,199,174,141", "中國移動": "139,138,137,136,135,134,159,158,157,150,151,152,147,188,187,182,183,184,178,198", "中國聯通": "130,131,132,146,156,155,166,186,185,145,175,176", "虛擬運營商": "170,171", "內部號碼": "123" } }
public class PhoneValidator { private static readonly Regex checktor = new Regex(@"^1\d{10}$"); public IDictionary segment = null; public PhoneValidator(IDictionary segment) { this.segment = segment; } public bool IsPhone(ref string tel) { if (string.IsNullOrEmpty(tel)) { return false; } tel = tel.Replace("+86-", "").Replace("+86", "").Replace("86-", "").Replace("-", ""); if (!checktor.IsMatch(tel)) { return false; } string s = tel.Substring(0, 3); if (segment.Count > 0 && !segment.Contains(s)) { return false; } return true; } }
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); CreatePhoneValidator(services); } private void CreatePhoneValidator(IServiceCollection services) { Hashtable segment = new Hashtable(); var coll = Configuration.GetSection("phone-segment").GetChildren(); foreach (var prefix in coll) { if (string.IsNullOrEmpty(prefix.Value)) continue; foreach (var s in prefix.Value.Split(',')) segment[s] = s; } var pv = new PhoneValidator(segment); services.AddSingleton<PhoneValidator>(pv); }
[Route("api/home")] [ApiController] public class HomeController : ControllerBase { PhoneValidator validator = null; public HomeController(PhoneValidator pv) { validator = pv; } [HttpGet("login")] public IActionResult Login(string phone) { bool accept = validator.IsPhone(ref phone); return new JsonResult(new { phone, accept }); } }
http://localhost:33868/api/home/login?phone=86-13800138000
https://github.com/lianggx/EasyAspNetCoreDemo/tree/master/Ron.PhoneTestgithub