Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript - Username Validation using Regex
Next article icon

JavaScript - Username Validation using Regex

Last Updated : 16 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are going to validate usernames in JavaScript. Username validation is a common requirement in user registration forms, ensuring that usernames meet the specific criteria

  • It must start with a letter.
  • Can contain letters, numbers, and underscores.
  • Must be between 3 and 16 characters long.

Simple Regular Expression-Based Validation

In this approach, we are using only simple regular expressions to validate usernames.

JavaScript
function validateUsername(username) {     const pattern = /^[a-zA-Z][a-zA-Z0-9_]{2,15}$/;     return pattern.test(username); }   //Driver Code Starts // Test cases console.log(validateUsername("user123")); console.log(validateUsername("_user"));   console.log(validateUsername("u"));       console.log(validateUsername("user_name123")); console.log(validateUsername("user@name"));  //Driver Code Ends 

Output
true false false true false 

In this example

  • ^ : Start of the string
  • [a-zA-Z] : The username must start with a letter (uppercase or lowercase).
  • [a-zA-Z0-9_] : The username can contain letters, numbers, and underscores.
  • {2,15} : The username must be between 3 and 16 characters long (since the first character is already matched, we use {2,15} for the remaining length).
  • $ : End

Combined Logic for More Customization

In some cases, using only regular expressions might not be enough, especially if you have more complex validation rules.

JavaScript
function validateUsername(username) {     if (username.length < 3) {         return "Username is too short.";     }     if (username.length > 16) {         return "Username is too long.";     }      // Regex to check valid characters: letters, numbers, dots, underscores     const pattern = /^[a-zA-Z0-9._]+$/;     if (!pattern.test(username)) {         return "Username contains invalid characters. Only letters, numbers, dots, and underscores are allowed.";     }      // Check that it doesn't start or end with a dot or underscore     if (username.startsWith('.') || username.startsWith('_')) {         return "Username cannot start with a dot or underscore.";     }     if (username.endsWith('.') || username.endsWith('_')) {         return "Username cannot end with a dot or underscore.";     }      return "Valid username."; }   //Driver Code Starts console.log(validateUsername("user.name")); console.log(validateUsername(".username")); console.log(validateUsername("username_")); console.log(validateUsername("us")); console.log(validateUsername("a_very_long_username_example")); console.log(validateUsername("valid_user123")); console.log(validateUsername("invalid#name")); //Driver Code Ends 

Output
Valid username. Username cannot start with a dot or underscore. Username cannot end with a dot or underscore. Username is too short. Username is too long. Valid username. Username contains invalid cha...

Next Article
JavaScript - Username Validation using Regex

H

hardiksm73
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-RegExp

Similar Reads

    How to Validate Email Address using RegExp in JavaScript?
    Validating an email address in JavaScript is essential for ensuring that users input a correctly formatted email. Regular expressions (RegExp) provide an effective and efficient way to check the email format.Why Validate Email Addresses?Validating email addresses is important for a number of reasons
    3 min read
    Form validation using the jbvalidator Plugin
    jbvalidator is a jQuery and Bootstrap based plugin which supports both client and server form validations. The provided HTML data attributes are easy to use and understand. The plugin gives multi-language facilities along with custom validation rules and messages.The plugin can be used by downloadin
    4 min read
    JavaScript Form Validation
    JavaScript form validation checks user input before submitting the form to ensure it's correct. It helps catch errors and improves the user experience.What we are going to CreateIn this article, we will guide you through creating a form validation application. This application will validate essentia
    10 min read
    JavaScript - How to Validate Form Using Regular Expression?
    To validate a form in JavaScript, you can use Regular Expressions (RegExp) to ensure that user input follows the correct format. In this article, we'll explore how to validate common form fields such as email, phone number, and password using RegExp patterns.1. Validating an Email AddressOne of the
    4 min read
    JavaScript regex - Validate Credit Card in JS
    To validate a credit card number in JavaScript we will use regular expression combined with Luhn's algorithm. Appling Luhn's algorithm to perform a checksum validation for added securityLuhn algorithm:It first sanitizes the input by removing any non-digit characters (e.g., spaces).It then processes
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences