using System.Text; using System.Text.RegularExpressions; namespace 落地页测试代码 { public class Validate { private static Regex RegNumber = new Regex("^[0-9]+$"); private static Regex RegNumberSign = new Regex("^[+-]?[0-9]+$"); private static Regex RegDecimal = new Regex("^[0-9]+[.]?[0-9]+$"); private static Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$"); //等价于^[+-]?\d+[.]?\d+$ private static Regex RegEmail = new Regex(@"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$");//w 英文字母或数字的字符串,和 [a-zA-Z0-9] 语法一样 private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]"); #region 用户名密码格式 /// <summary> /// 返回字符串真实长度, 1个汉字长度为2 /// </summary> /// <returns>字符长度</returns> public static int GetStringLength(string stringValue) { return Encoding.Default.GetBytes(stringValue).Length; } /// <summary> /// 检测用户名格式是否有效 /// </summary> /// <param name="userName"></param> /// <returns></returns> public static bool IsValidUserName(string userName) { int userNameLength = GetStringLength(userName); if (userNameLength >= 4 && userNameLength <= 20 && Regex.IsMatch(userName, @"^([\u4e00-\u9fa5A-Za-z_0-9]{0,})$")) { // 判断用户名的长度(4-20个字符)及内容(只能是汉字、字母、下划线、数字)是否合法 return true; } else { return false; } } /// <summary> /// 密码有效性 /// </summary> /// <param name="password"></param> /// <returns></returns> public static bool IsValidPassword(string password) { return Regex.IsMatch(password, @"^[A-Za-z_0-9]{6,16}$"); } #endregion #region 数字字符串检查 /// <summary> /// int有效性 /// </summary> /// <param name="val"></param> /// <returns></returns> static public bool IsValidInt(string val) { return Regex.IsMatch(val, @"^[1-9]\d*\.?[0]*$"); } /// <summary> /// 是否数字字符串 /// </summary> /// <param name="inputData">输入字符串
C# 常用类型校验Validate
最新推荐文章于 2023-01-13 21:00:00 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)