From f94269c0d134ca737d7c3e4799b7b3e0c13f4dd8 Mon Sep 17 00:00:00 2001
From: Calixte Denizet <calixte.denizet@gmail.com>
Date: Thu, 10 Dec 2020 15:38:31 +0100
Subject: [PATCH] JS -- add function eMailValidate used to validate an email
 address

---
 src/scripting_api/aform.js          | 12 ++++++++++++
 src/scripting_api/initialization.js |  2 +-
 test/unit/scripting_spec.js         | 16 ++++++++++++++++
 3 files changed, 29 insertions(+), 1 deletion(-)

diff --git a/src/scripting_api/aform.js b/src/scripting_api/aform.js
index 7b0d07ddc..9165a01ac 100644
--- a/src/scripting_api/aform.js
+++ b/src/scripting_api/aform.js
@@ -37,6 +37,14 @@ class AForm {
       "m/d/yy HH:MM",
     ];
     this._timeFormats = ["HH:MM", "h:MM tt", "HH:MM:ss", "h:MM:ss tt"];
+
+    // The e-mail address regex below originates from:
+    // https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
+    this._emailRegex = new RegExp(
+      "^[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])?)*$"
+    );
   }
 
   _parseDate(cFormat, cDate) {
@@ -577,6 +585,10 @@ class AForm {
       this.AFDate_KeystrokeEx(this._timeFormats[pdf]);
     }
   }
+
+  eMailValidate(str) {
+    return this._emailRegex.test(str);
+  }
 }
 
 export { AForm };
diff --git a/src/scripting_api/initialization.js b/src/scripting_api/initialization.js
index 85fafd6ff..9696bfd9a 100644
--- a/src/scripting_api/initialization.js
+++ b/src/scripting_api/initialization.js
@@ -92,7 +92,7 @@ function initSandbox({ data, extra, out }) {
   out.zoomtype = ZoomType;
 
   for (const name of Object.getOwnPropertyNames(AForm.prototype)) {
-    if (name.startsWith("AF")) {
+    if (name !== "constructor" && !name.startsWith("_")) {
       out[name] = aform[name].bind(aform);
     }
   }
diff --git a/test/unit/scripting_spec.js b/test/unit/scripting_spec.js
index b30ef1a71..02ddc8ac2 100644
--- a/test/unit/scripting_spec.js
+++ b/test/unit/scripting_spec.js
@@ -1202,5 +1202,21 @@ describe("Scripting", function () {
         }
       });
     });
+
+    describe("eMailValidate", function () {
+      it("should validate an e-mail address", function (done) {
+        Promise.all([
+          myeval(`eMailValidate(123)`).then(value => {
+            expect(value).toEqual(false);
+          }),
+          myeval(`eMailValidate("foo@bar.com")`).then(value => {
+            expect(value).toEqual(true);
+          }),
+          myeval(`eMailValidate("foo bar")`).then(value => {
+            expect(value).toEqual(false);
+          }),
+        ]).then(() => done());
+      });
+    });
   });
 });