Skip to content

Instantly share code, notes, and snippets.

@timoschinkel
Last active June 28, 2024 15:36
Show Gist options
  • Save timoschinkel/fe409ce4e019138778d4f0d9d1879e1e to your computer and use it in GitHub Desktop.
Save timoschinkel/fe409ce4e019138778d4f0d9d1879e1e to your computer and use it in GitHub Desktop.
Validating an email address using different methods
// Using AWS Cognito via TypeScript
import { AdminCreateUserCommand, AdminDeleteUserCommand, CognitoIdentityProviderClient } from '@aws-sdk/client-cognito-identity-provider';
const addresses = [
// valid
'[email protected]',
'[email protected]',
'"name..name"@example.com',
'name@localhost',
'nå[email protected]',
'aA0!#$%&\'*+-/=?^_`{|}[email protected]',
// invalid
'name.example.com',
'[email protected]',
'[email protected]',
'[email protected]',
'<name>@example.com',
// invalid host names
'[email protected]',
'[email protected]',
'[email protected]',
// update 2024-06-28
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
];
const cognito = new CognitoIdentityProviderClient({
region: 'eu-west-1'
});
const userPoolId = process.env.USER_POOL_ID;
addresses.forEach(async (address) => {
await cognito.send(new AdminCreateUserCommand({
UserPoolId: userPoolId,
Username: address,
MessageAction: 'SUPPRESS',
})).then(async () => {
console.log(`${address} is valid`);
// clean up
await cognito.send(new AdminDeleteUserCommand({
UserPoolId: userPoolId,
Username: address
})).catch((error) => {
console.log(`Unable to clean up ${address} - ${error}`);
});
}).catch((error) => {
console.log(`${address} is NOT valid - ${error}`);
});
});
// Using Model Annotations in .NET 6
using System.ComponentModel.DataAnnotations;
using System;
var addresses = new string[] {
// valid
"[email protected]",
"[email protected]",
"\"name..name\"@example.com",
"name@localhost",
"nå[email protected]",
"aA0!#$%&'*+-/=?^_`{|}[email protected]",
// invalid
"name.example.com",
"[email protected]",
"[email protected]",
"[email protected]",
"<name>@example.com",
// invalid host names
"[email protected]",
"[email protected]",
"[email protected]",
// update 2024-06-28
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
};
foreach (var address in addresses)
{
var obj = new DomainObject { EmailAddress = address };
try
{
Validator.ValidateObject(obj, new ValidationContext(obj, null, null), true);
Console.WriteLine($"{address} is valid");
}
catch (ValidationException exception)
{
Console.WriteLine($"{address} is NOT valid - {exception.Message}");
}
}
class DomainObject
{
[EmailAddress]
public string? EmailAddress { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment