GeekJock
GeekJock

Reputation: 11326

Rails route constraint for base64 encoded parameter

I have the following route:

get '/:id', to: 'articles#show'

How do I have the route only match if the :id is a base64 encoded string? I've tried regexp unsuccessfully.

EDIT: I've tried using the regex suggested in one of the responses.

get /:id, to: 'articles#show', constraints: { id: /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/}

This leads to the following error in Rails:

Regexp anchor characters are not allowed in routing requirements:
/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/

Upvotes: 0

Views: 218

Answers (1)

Justin Auvil
Justin Auvil

Reputation: 68

From the Rails routing guide located at https://guides.rubyonrails.org/v2.3.11/routing.html

get '/:id', to: 'articles#show', requirements: {id: **Your Regex**}

This route would only hit if the :id parameter hit on the Regex.

As for a regex that will successfully match a base64 string, answers to the following StackOverflow question provide lots of options. RegEx to parse or validate Base64 data

Update: Remove the anchor characters from your Regex. Source: Rails custom route with constraints - regexp anchor characters are not allowed in routing requirements

Upvotes: 1

Related Questions