Thomas Smeman
Thomas Smeman

Reputation: 195

Firebase data validation based on timestamps

I need a validation rule that checks if the end date is after the start date, so the period is valid. I have found a couple resources, but I couldn't use them to get what I need. Perhaps for someone else it is of some use.

Basically, I have document coming in in cloud firestore and I need to check if the value dateEnd > dateStart. Both come from the same request. I would rather store the values as day/month/year instead of storing them as a timestamp value. However, if there is no other solution than to use timestamps, I could use that.

I can't get any further than this:

match /organisations/{orgID}/people/{userID} {
    allow create: if(dateEnd > dateStart)
}

Thanks in advance for your help

Upvotes: 0

Views: 285

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83153

If you use a date format like YYYYMMDD (which allows to lexicographic order dates), the following should do the trick. It would also work with timestamps in milliseconds.

match /organisations/{orgID}/people/{userID}
  allow create: if request.resource.data.dateEnd > request.resource.data.dateStart;
}

As explained in the doc, "When writing data ... the request.resource variable contains the future state of the document".

I would suggest you watch the official video about security rules, a must watch...


If you absolutely need to store the values as DD/MM/YYYY in the Firestore document you should have two pairs of fields: a dateEnd/dateStart pair of field with format DD/MM/YYYY, and another pair of fields, e.g. dateEndForRules/dateStartForRules with format YYYYMMDD that you only use in the Security rules.

Upvotes: 2

Related Questions