Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx for computer name validation (cannot be more than 15 characters long, be entirely numeric, or contain the following characters...)

Tags:

regex

I have these requirements to follow:

Windows computer name cannot be more than 15 characters long, be entirely numeric, or contain the following characters: ` ~ ! @ # $ % ^ & * ( ) = + _ [ ] { } \ | ; : . ' " , < > / ?.

I want to create a RegEx to validate a given computer name.

I can see that the only permitted character is - and so far I have this:

/^[a-zA-Z0-9-]{1,15}$/

which matches almost all constraints except the "not entirely numeric" part.

How to add last constraints to my RegEx?

like image 761
Mariusz Ignatowicz Avatar asked Oct 28 '25 20:10

Mariusz Ignatowicz


1 Answers

You could use a negative lookahead:

^(?![0-9]{1,15}$)[a-zA-Z0-9-]{1,15}$

Or simply use two regular expressions:

^[a-zA-Z0-9-]{1,15}$
AND NOT
^[0-9]{1,15}$;

Here is a live example:

var regex1 = /^(?![0-9]{1,15}$)[a-zA-Z0-9-]{1,15}$/;
var regex2 = /^[a-zA-Z0-9-]{1,15}$/;
var regex3 = /^[0-9]{1,15}$/;

var text1 = "lklndlsdsvlk323";
var text2 = "4214124";

console.log(text1 + ":", !!text1.match(regex1));
console.log(text1 + ":", text1.match(regex2) && !text1.match(regex3));
console.log(text2 + ":", !!text2.match(regex1));
console.log(text2 + ":", text2.match(regex2) && !text2.match(regex3));
like image 113
ssc-hrep3 Avatar answered Oct 31 '25 11:10

ssc-hrep3