DEV Community

Regex Bootcamp (or Nobody Seems to be Using HTML5 Validation)

George Jempty on January 27, 2019

In this post I will be referring back to simplified versions of my regex's (regular expressions) from my previous post on form validation. That re...
Collapse
 
qm3ster profile image
Mihail Malo

Regexes are easy and useful in the backend, but I feel like they are extremely user-unfriendly.
How do I explain the "requested format" to the end user?
That's why I feel like something like a declaratively composed validator is more useful, since it can say which attribute of the string is wrong.

Collapse
 
dexygen profile image
George Jempty

You realize regex's ARE declarative? "Common declarative languages include those of database query languages (e.g., SQL, XQuery), regular expressions": en.wikipedia.org/wiki/Declarative_...

Collapse
 
qm3ster profile image
Mihail Malo • Edited

Sure, and you could even reverse-engineer some messages, but you'd get something like

Phone must begin with "00" or "+" or nothing, followed by "1" or "7" or "20" or "27" or "3...

Whereas with a proper syntax description you could automatically insert a "+", delete a leading "00", and if the following two digits aren't a real country code have an informative error like

Please include the country code in the phone number

Collapse
 
anargh profile image
anargh

"you cannot assign a regex defined as a literal to a variable"

I'm not sure if I got this right and could probably a stupid question. But by saying you cannot assign, do you mean that the following is invalid or frowned upon?

const myRegex = /^\d{0,5}$/;
Collapse
 
dexygen profile image
George Jempty

Hmm I could be wrong I was trying something like this but it was barfing on the \d I think, as soon as I used new RegExp and escaped the \d with a slash it worked.