I'm trying to have a single JSON file to validate data both in front (JS) and back (PHP). I cannot figure out how to have my pattern in a json string, PHP won't convert it. Here's what I'd like to use (email validation):
'{"name":"email", "pattern":"^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$"}'
I suppose there's something in pattern that doesn't get treated as a string? This as it is, won't convert to an object in PHP. I shouldn't have to escape anything but I might be wrong...
thanks
Edit: Tried this as suggested in comments:
json_decode('{"name":"email", "pattern":"^[a-z0-9]+(\\.[_a-z0-9]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,15})$"}'); ==> NULL
The problem are the backslashes \
. Use two to signal that there is one and it will work well:
{"name":"email","pattern":"^[a-z0-9]+(\\.[_a-z0-9]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,15})$"}
The above is valid JSON but will cause trouble as PHP string, because \\
will already be interpreted as one \
before it is passed to json_decode()
, and we're back where we started from. As deceze kindly pointed out in the comments, this can be solved by adding four backslashes:
{"name":"email","pattern":"^[a-z0-9]+(\\\\.[_a-z0-9]+)*@[a-z0-9-]+(\\\\.[a-z0-9-]+)*(\\\\.[a-z]{2,15})$"}
Or by immediately passing the contents from file_get_contents()
(or similar) to json_decode()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With