Skip to content

Instantly share code, notes, and snippets.

@greghendershott
Created November 3, 2017 21:48
Show Gist options
  • Save greghendershott/4019ddefeba6d928637f797e8f0f8ef6 to your computer and use it in GitHub Desktop.
Save greghendershott/4019ddefeba6d928637f797e8f0f8ef6 to your computer and use it in GitHub Desktop.
Validating email addresses
#lang racket/base
(require racket/match
net/dns)
(provide validate-address)
(define (validate-address s)
(match s
[(regexp "^([^@]+)@(.+)$" (list _ user domain))
(let/ec return
(unless (valid-user? user ) (return "Not an acceptable user"))
(unless (valid-domain? domain) (return "Not an acceptable domain"))
'valid)]
[_ "Doesn't seem to be the form of an email address"]))
(define (valid-user? s)
(not (member s '("postmaster" "abuse" "noc"))))
(define ns (or (dns-find-nameserver) "8.8.8.8"))
(define (valid-domain? s)
(with-handlers ([exn:fail? (λ _ #f)])
(dns-get-address ns
(dns-get-mail-exchanger ns s))))
(module+ test
(require rackunit)
(check-equal? (validate-address "blergh")
"Doesn't seem to be the form of an email address")
(check-equal? (validate-address "[email protected]")
"Not an acceptable user")
(check-equal? (validate-address "[email protected]")
"Not an acceptable domain")
(check-equal? (validate-address "[email protected]") 'valid))
@greghendershott
Copy link
Author

An example of validating an email address to be used as part of a user signup (authentication) system. Note this does network I/O to validate the domain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment