Dave Kiss
Dave Kiss

Reputation: 10495

Check user input is valid CSS width value

I'm allowing a user to type in a width value that I need to ensure is a valid CSS width value.

Using regex, how would I get two matches from the user input where $matches[0] = a number value AND $matches[1] = either px or %?

Thanks!

Upvotes: 0

Views: 872

Answers (2)

Bob Ramsey
Bob Ramsey

Reputation: 617

This is the first response on a google search on how to confirm that a string is valid css. So that's a pretty good answer. :) I would add rem and em to the regex. (\d*)(px|%|em|rem).

And depending on the situation, might want to check that \d is greater than or equal to 0, unless you want people to be able to say that something is -100px wide or something. And allow either '0' or 0.,

Upvotes: 0

Ioan Alexandru Cucu
Ioan Alexandru Cucu

Reputation: 12279

(\d*)(px|%)?

First captured item will be the number, the second captured item will be px or %.

Upvotes: 2

Related Questions