Skip to Content
Menu

isAlphanumeric()

Boolean check if a string is made up of only letters and/or numbers.

JavaScript April 4, 2021

Usage

JavaScript
nebula.isAlphanumeric(character)

Parameters

string
(Required) (String) The character or word to check
Default: None

allowWords
(Optional) (Boolean) Allow strings longer than 1 character
Default: true

Parameter Notes

The allowWords can be set to false to help detect meta keys vs. single character keys.

Request or provide clarification »

Examples

Call this function inside of a keydown to test the key.

JavaScript
jQuery("input#whatever").on('keydown paste', function(e){
    if ( nebula.isAlphanumeric(e.key, false) ){ //False here indicates we only want single characters– so ignore meta keys like Escape
        //Do stuff if the key was a letter or number
    }
});

Demo


Press a key to test if it is alphanumeric.

Remember: meta key names (like "Enter", "Shift", "Escape", etc.) are strings, so they will be detected as alphanumeric words! Set the allowWords parameter to false to check single characters.

Key Pressed: 

Alphanumeric? (Single Character) 

Alphanumeric? (Word) 

Additional Notes

This allows lowercase or uppercase letters or numbers.

Was this page helpful? Yes No


    A feedback message is required to submit this form.


    Please check that you have entered a valid email address.

    Enter your email address if you would like a response.

    Thank you for your feedback!

    Source File

    Located in /assets/js/modules/utilities.js on line 715.

    No Hooks

    This function does not have any filters or actions available. Request one?
    JavaScript
    nebula.isAlphanumeric = function(string = '', allowWords = true){
        if ( !allowWords && string.length > 1 ){ //Ignore meta keys whose "character" is a word (not a letter)
            return false;
        }
    
        const alphanumericRegex = new RegExp('^[a-zA-Z0-9]+$');
        if ( string && alphanumericRegex.test(string) ){
            return true;
        }
    
        return false;
    };
    

    Override

    To override or disable this JavaScript function, simply redeclare it with the exact same function name.

    JavaScript
    nebula.isAlphanumeric = function(string, allowWords){
        //Write your own code here, leave it blank, or return false.
    }