mardi 16 juin 2020

How to make HTML5 email validation regex work in C++?

I am trying to validate email both on the client-side and on the server-side. The client-side is JavaScript(web front-end). The server-side is written in C++11.

The regex I am using to validate email is provided by the HTML standard (here)[https://html.spec.whatwg.org/multipage/input.html#e-mail-state-(type=email)]. I am reproducing it here for quick reference:

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/

The validation works on the client-side using JavaScript. But the server-side validation using std::regex_match fails.

Following is the C++ code to check valid email:

bool is_valid_email(std::string email)
{
    // Regex from HTML5 spec.
    static std::regex const email_regex {R"(/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/)"};

    return std::regex_match(email, email_regex);
}

What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire