php – Validate google api key


I'm making an application, where I'll have to validate a google maps API key. The problem is, I don't know what patterns it follows:


Here it is visible that there are upper and lower case letters, numbers and dashes. But will it always be like this?

Does anyone know the pattern of these keys, and how to do this with JS and PHP?


var inputstr="A3aa622-_";
var regex=/^[A-Za-z0-9-_]{30,50}$/g;
if (regex.test(inputstr)){


Assuming the key is exactly 39 characters long; It is formed by alphanumeric characters (letters and numbers), in any case (uppercase or lowercase); And it can have dashes - and underlines _ .

Here are the codes in JS and PHP capable of doing this pre-validation*:

JavaScript code:

function is_valid_key( key )
    if( key.length != 39 ) return false;
    var regx = new RegExp("^[A-Za-z0-9-_]+$");
    return regx.test(key);

PHP code:

function is_valid_key( $key )
    if( strlen( $key ) != 39 ) return false;
    return preg_match( '/^[a-zA-Z0-9-_]+$/', $key );
  • User @Inkeliz is right, the only way to validate the key is via a GET/POST in the Google API, so the above code is just a pre-validation in order to avoid unnecessary GET overhead and POSTs on the network.

Hope this helps!

Scroll to Top