Skip to content

Commit 7766692

Browse files
committed
Handle emails better
1 parent 4b8a4bb commit 7766692

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

__tests__/Str-test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,12 @@ describe('Str.sanitizeURL', () => {
113113
describe('Str.isValidEmail', () => {
114114
it('Correctly identifies valid emails', () => {
115115
expect(Str.isValidEmail('abc@gmail.com')).toBeTruthy();
116+
117+
// Real-world examples from production testing
118+
expect(Str.isValidEmail('zz@gmail.com')).toBeTruthy();
119+
expect(Str.isValidEmail('zz+1@gmail.com')).toBeTruthy();
120+
expect(Str.isValidEmail('dabeamanator+20251120@gmail.com')).toBeTruthy();
121+
116122
expect(Str.isValidEmail('test@gmail')).toBeFalsy();
117123
expect(Str.isValidEmail('@gmail.com')).toBeFalsy();
118124
expect(Str.isValidEmail('usernamelongerthan64charactersshouldnotworkaccordingtorfc822whichisusedbyphp@gmail.com')).toBeFalsy();
@@ -192,6 +198,12 @@ describe('Str.isValidEmail', () => {
192198
// TLD too long
193199
expect(Str.isValidEmail('a@a.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkl')).toBeFalsy();
194200
});
201+
202+
it('Handles undefined and null values gracefully', () => {
203+
expect(Str.isValidEmail(undefined)).toBeFalsy();
204+
expect(Str.isValidEmail(null)).toBeFalsy();
205+
expect(Str.isValidEmail('')).toBeFalsy();
206+
});
195207
});
196208

197209
describe('Str.isValidPhoneFormat', () => {

lib/str.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -406,7 +406,24 @@ const Str = {
406406
* @returns True if the string is an email
407407
*/
408408
isValidEmail(str: string): boolean {
409-
const unicodeVersion = Punycode.toUnicode(str);
409+
// Return false if str is undefined, null, or not a string
410+
if (!str || typeof str !== 'string') {
411+
return false;
412+
}
413+
414+
// Safely convert to unicode using punycode, handling any errors
415+
let unicodeVersion: string | undefined;
416+
try {
417+
unicodeVersion = Punycode.toUnicode(str);
418+
// Ensure unicodeVersion is a valid string before using it
419+
if (!unicodeVersion || typeof unicodeVersion !== 'string') {
420+
unicodeVersion = str;
421+
}
422+
} catch (error) {
423+
// If punycode conversion fails, fall back to original string
424+
unicodeVersion = str;
425+
}
426+
410427
if (String(unicodeVersion).match(Constants.CONST.REG_EXP.EMOJI_RULE)) {
411428
return false;
412429
}

0 commit comments

Comments
 (0)