So I'm working on an application where Javascript will first validate the email using a regex and then once sent to PHP, PHP will verify the user did not modify any of the javascript and validate the info again with filter_var.

For example, in JS I validate with this regex first using .test()


This is a regex I picked up off emailregex.com and seems to validate everything fairly well.

After the form is submitted I use php filter_var($email, FILTER_VALIDATE_EMAIL) to once again validate.

Does this method have any downsides and would there be any better ways to do this?

  • 2
    \$\begingroup\$ You should include the rest of the code that does this work, as it is there is not enough code present to meaningfully review properly. \$\endgroup\$ – Phrancis Mar 29 '17 at 4:38
  • \$\begingroup\$ You will find some usefull informations about email addresses here: en.wikipedia.org/wiki/Email_address#Examples \$\endgroup\$ – Toto Mar 29 '17 at 8:08

Client-side validation is for user convenience and, marginally, to reduce load on your server... the user will be notified more quickly of an error, speeding up the process of correcting it, and the user's computer handles the processing.

Server-side validation is for security and safety, because you can't trust the client. Users can disable or disrupt JavaScript (sometimes by accident), or they can use tools like Postman to fake HTTP requests.

Sounds like you are doing things correctly.

One downside that comes to mind immediately is when your client-side and server-side validation don't match. For example, if your client-side validation is stricter (accidentally), you could end up with a scenario where things look secure but are actually vulnerable to HTTP request hacking. This can be mitigated with lots and lots of automated testing of both the client-side and server-side services.

Another downside is code replication. Keeping both the client and server up-to-date and in sync with ever-changing requirements can be tedious and error prone, and sometimes server-side and client-side technologies aren't exactly one-for-one, making it difficult to engineer identical solutions. Once again, lots of automated testing can mitigate errors and ensure that both client and server are in sync.

| improve this answer | |
  • \$\begingroup\$ I ended up using the same regex on both the client and backend this way it will have no confusion. A bit of an off topic question but when would be a good time to use htmlspecialchars? \$\endgroup\$ – Joe Scotto Mar 29 '17 at 2:34
  • \$\begingroup\$ The regex may be the same, but that doesn't mean that that the regex parsers are the same. While I think that you are safe with this particular regex, keep in mind that regexes in PHP and JS are different. Nothing can replace a good test suite. \$\endgroup\$ – JDB still remembers Monica Mar 29 '17 at 2:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.