Validate string using RegularExpressions in C# and VB.Net

mahesh213
 
on Dec 08, 2020 12:25 AM
1037 Views

Hi,

i have username my requirement is that i need to do some validations for that i need to allow only alphabets (letters), underscore and one (') character

Rather than this i don't want to allow any characters, numbers

Could you please help me

Ex:

abc-ded's -valid

abc-def -valid

abc.def -invalid

-abc -invalid

abc@def -invalid 

public void checkUsernamevalid()
{
    string username = "abc-def's
    if ()
    {
        //valid block
    }
    else {
        //invalid
    }
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Dec 08, 2020 05:26 AM

Hi mahesh213,

Use RegularExpressions to validate.

Check this example. Now please take its reference and correct your code.

Code

C#

public bool checkUsernamevalid(string username)
{
    bool isValid = false;
    var regx = new System.Text.RegularExpressions.Regex("^[a-zA-Z-']*$");
    if (regx.IsMatch(username))
    {
        if (username.StartsWith("-"))
        {
            isValid = false;
        }
        else
        {
            isValid = true;
        }
    }
    else
    {
        isValid = false;
    }

    return isValid;
}

VB.Net

Public Function checkUsernamevalid(ByVal username As String) As Boolean
    Dim isValid As Boolean = False
    Dim regx = New System.Text.RegularExpressions.Regex("^[a-zA-Z-']*$")
    If regx.IsMatch(username) Then
        If username.StartsWith("-") Then
            isValid = False
        Else
            isValid = True
        End If
    Else
        isValid = False
    End If

    Return isValid
End Function