Program to Validate Username

Program to Validate Username

Today’s problem, write a program to validate username, similar to the Instagram username validation program, I came up with a simple solution in C++. The problem is very simple, we just need to take care of the rules and limits stated below.

Conditons and Rules for Username

  • Can contain Numbers
  • No special Characters
  • Length less than 30 characters
  • Can have all Alphabets Uppercase & Lowercase
  • Can have only one [.] period or [ _ ] underscore

$ new function found : isalnum()

So, We have to allow all alphanumeric characters, this can be checked by their ASCII value but to my surprise, I found out that there was an inbuilt function called isalnum() that checks whether the given character is an alphabet or a number and returns true/false, this made the validate username process much easier.

Program to Validate Username in C++

#include <iostream>
using namespace std;

int validates(string username)
{
    int special = 0, l = username.length();
    
    //check length is 0 or more than 30
    if (l == 0 || l > 30)
        return 0;

    for (int i = 0; i < l; i++)
    {
        char s = username.at(i);

        //no spaces allowed
        if (s == ' ')
            return 0;

        //characters other than alphabets and numbers    
        if (isalnum(s))
            continue;
        else
        {
            //periods and underscore allowed but only one
            if (s == '_' || s == '.')
            {
                special++;
                if (special > 1)
                    return 0;
            }
            else
                return 0;
        }
    }
    return 1;
}

int main()
{
    if (validates("Abhi123"))
        cout << "Valid Username";
    else
        cout << "Invalid Username";
    return 0;
}

Output

Input:Matrix_Read
Output:Valid 

Input:Matrix Read
Output: Invalid

Input:Matrixread123_
Output: Valid 

Conclusion

As we can see from the code, isalnum() saved us a lot of time. I guess I’ll be using this function more from now on what do you say? This post is part of my #30DaysChallenge to write a blog post every day on what I learn.

See you tomorrow, Happy Coding~ Abhiram Reddy

Leave a Reply

Your email address will not be published. Required fields are marked *

Popular posts