3

How can I verify if an incoming field is a valid e-mail? Is there a way to use string-functions or anything in Firestore security rules?

Example:

Let's say I have a Create-Request with a field called "email". In my Firestore security rules, I would like to check if the email is a valid email address:

  • contains '@'
  • ends with either .xx or .xxx (a casual country-domain-ending)
  • has a '.' before the last three or two letters of the email
  • the '.' does not follow directly after the '@' - at least two letters have to be in-between

So that e.g. example@emailprovider.com gets accepted, but not example@.com.

I know that this check is quite extensive and further would like to know if it makes sense to introduce such a validation to security rules?

linus_hologram
  • 1,595
  • 13
  • 38

2 Answers2

3

You can use rules.String.matches.

See

Performs a regular expression match on the whole string.

A regular expression using Google RE2 syntax.

If you want to set only email address then It's necessary to validate the field as email address.

Community
  • 1
  • 1
zkohi
  • 2,486
  • 1
  • 10
  • 20
2

I found an example of a regex (and adjusted a bit):

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,5}$

The source of this is at the bottom of the following page:

https://firebase.google.com/docs/reference/security/database/regex

You should also take into account the note as well:

Note: THIS WILL REJECT SOME VALID EMAILS. Validating email address in regular expressions is difficult in general. See this site for more depth on the subject.

Gyuri Majercsik
  • 2,141
  • 1
  • 17
  • 29