How can I validate a string to only allow alphanumeric characters in it?

后端 未结 10 1244
执笔经年
执笔经年 2020-12-12 15:06

How can I validate a string using Regular Expressions to only allow alphanumeric characters in it?

(I don\'t want to allow for any spaces either).

10条回答
  •  不知归路
    2020-12-12 16:00

    While I think the regex-based solution is probably the way I'd go, I'd be tempted to encapsulate this in a type.

    public class AlphaNumericString
    {
        public AlphaNumericString(string s)
        {
            Regex r = new Regex("^[a-zA-Z0-9]*$");
            if (r.IsMatch(s))
            {
                value = s;                
            }
            else
            {
                throw new ArgumentException("Only alphanumeric characters may be used");
            }
        }
    
        private string value;
        static public implicit operator string(AlphaNumericString s)
        {
            return s.value;
        }
    }
    

    Now, when you need a validated string, you can have the method signature require an AlphaNumericString, and know that if you get one, it is valid (apart from nulls). If someone attempts to pass in a non-validated string, it will generate a compiler error.

    You can get fancier and implement all of the equality operators, or an explicit cast to AlphaNumericString from plain ol' string, if you care.

提交回复
热议问题