Check whether string contains uppercase letters

I want to create a password validation method so i want to check whether sring contains at least 1 uppercase letter... how do i do this

        public void ChangePassword(string UserID, string oldPassword, string newPassword)
        {
            if ( IsValidPassword(UserID, oldPassword) )
            {
                if (newPassword.Length >= 8)
                    if (newPassword.Contains(); // here i want to check for uppercase letter
                        Password = newPassword;
            }
            else
                MessageBox.Show("Password must be at lease 8 characters long and must contain at lease 1 uppercase letter")
        }

 




Answer this question

Check whether string contains uppercase letters

  • jph290

    bool hasUCase = s.ToLower() != s;

  • 龙二

    Or you can do it like this, without string instancing/comparing:


    private bool HasCapitals(string text) {
        foreach (char c in text) {
            if (char.IsUpper(c)) return true;
        }
        return false;
    }

     



  • John Land

    string password = "passWord";

    foreach (char var in password)

    {

    if(var.ToString() == char.ToUpper(var).ToString())

    Console.WriteLine(var); //Its UPPERCASE

    }



  • Ben Chambers

    Thats the ticket!

    Didn't know IsUpper existed. lol.

  • sb_pariveda

    I would suggest looking at System.Text.RegularExpressions.Regex

    You can create a Regex object whose string is set to "[A-Ba-b]", if you check the documentation there's probably an escape code that covers alphanumeric characters.  You can create a more advanced expression for validating the password (e.g. must contain at least one upper case character and a number, but no symbols or spaces).

    You can grab free regex tools for testing regular expressions rather then debugging your code over and over, two I know of are "The Regulator" and "Regex Workshop". Both of these are written in .NET and one of them (I forget which) will also generate the code you need for the regex you've created.

    Hope that helps,
    Shaun


  • Check whether string contains uppercase letters