How to validate a string value using regex (Regular Expression)

in #development6 years ago (edited)

regex.jpg

Good day my fellow developers, I have been a developer since 2004.

This is my first blog post and there will be a lot more to come in the near future, about development, new technologies and crypto-currencies

Today I am going to show you how to validate string using regular expression. I have create a helper class along with some unit test that can be downloaded from my GitHub

In the solution you will see a class library helper project with-in the project you will see the RegexValidator.cs class, I will be explaining how to use this class.

RegexValidator.cs

namespace Helpers
{
    public class RegexValidator
    {

        public enum ValidationType
        {
            InternationalMobile,
            Email,
            IPAddress,
            Trust,
            CompanyRegistation,
            AlphaChars,
            Numeric,
            BitCoinAddress,
            EthereumAddress
        }

        private string ValidInternationalMobileRegString = @"(^\+[1-9]{1}[0-9]{3,14}$)*[0-9{17}]";
        private string ValidEmailRegexString = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
        private string ValidIPAddressRegexString = @"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b";
        private string ValidTrustRegexString = @"^IT[0-9]{5}[/][0-9]{4}$";
        private string ValidCompanyRegNotRegexString = @"^IT[0-9]{5}[/][0-9]{4}$";
        private string ValidAlphaCharRegexString = "^[a-zA-Z]+$";
        private string ValidNumericRegexString = "^[0-9]*$";
        private string ValidBitcoinRegexSting = "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$";
        private string ValidEthereumRegexSting = "^0x?[0-9a-f]{40}$";

        private ValidationType validationType;
        private bool isCustomRegularExpression = false;
        private string regularExpressionString = "";


        public RegexValidator(ValidationType ValidationType)
        {
            validationType = ValidationType;
        }

        public RegexValidator(string RegularExpression)
        {
            isCustomRegularExpression = true;
            regularExpressionString = RegularExpression;
        }


        public bool Validate(string value)
        {
            System.Text.RegularExpressions.Regex regularExpression = new System.Text.RegularExpressions.Regex(getRegularExpressionString());

            return regularExpression.IsMatch(value);
        }

        public bool Validate(string value, System.Text.RegularExpressions.RegexOptions options)
        {
            System.Text.RegularExpressions.Regex regularExpression = new System.Text.RegularExpressions.Regex(getRegularExpressionString(), options);

            return regularExpression.IsMatch(value);
        }

        private string getRegularExpressionString()
        {

            if (isCustomRegularExpression)
            {
                return regularExpressionString;
            }

            switch (validationType)
            {
                case ValidationType.InternationalMobile:
                    return ValidInternationalMobileRegString;
                case ValidationType.Email:
                    return ValidEmailRegexString;
                case ValidationType.IPAddress:
                    return ValidIPAddressRegexString;
                case ValidationType.Trust:
                    return ValidTrustRegexString;
                case ValidationType.CompanyRegistation:
                    return ValidCompanyRegNotRegexString;
                case ValidationType.AlphaChars:
                    return ValidAlphaCharRegexString;
                case ValidationType.Numeric:
                    return ValidNumericRegexString;
                case ValidationType.BitCoinAddress:
                    return ValidBitcoinRegexSting;
                case ValidationType.EthereumAddress:
                    return ValidEthereumRegexSting;
                default:
                    break;
            }

            return "";
        }
    }
}

When instantiating the RegexValidator class, there is 2 constructors

RegexValidator(ValidationType ValidationType)
RegexValidator(string RegularExpression)

When using the constructor with ValidationType signature you provide an enumerated value that is used to set ValidationType options which a set of commonly defined regular expression. These commonly regular expression is declared as private stings inside the class. See Enum below:

    public enum ValidationType
        {
            InternationalMobile,
            Email,
            IPAddress,
            Trust,
            CompanyRegistation,
            AlphaChars,
            Numeric,
            BitCoinAddress,
            EthereumAddress
        }  

When using the contactor with the RegularExpression signature it allows you to pass through your own regular expression.
The class has 2 overloading method to valid your string value that will return a Boolean value, true = string is valid and false when sting is invalid.

public bool Validate(string value)

public bool Validate(string value, System.Text.RegularExpressions.RegexOptions options)

Parameters:
value = String to be validated
options = Provides enumerated values to use to set regular expression options.

Unit test can be seen in the unit test project in the UnitTestRegexValidator.cs.

Below is an test method example of using the RegexValidator class:

    [TestMethod]
        public void ValidateEmailAddress()
        {
            //arrange
            string email = "[email protected]";

            //act
            Helpers.RegexValidator emailValidator = new Helpers.RegexValidator(Helpers.RegexValidator.ValidationType.Email);

            //assert
            Assert.IsTrue(emailValidator.Validate(email));
        }

To read more about regular expression go visit This Page

Sort:  

Congratulations @andrebarn! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

You published your First Post
You got a First Vote

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!