Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to validate email in clojure

I want to validate a email using clojure. How can I do it.

(defn validate-email [email]

    )

I want to know how will be the function body writeen using regular expressions.

like image 219
Manish Singh Avatar asked Jul 05 '26 12:07

Manish Singh


2 Answers

Here is an example of a simple function that will check input email string against simple regexp:

(defn validate-email [email]
  (re-matches #".+\@.+\..+" email))

It will return input email if it matches .+\@.+\..+ regexp and nil otherwise:

(validate-email "[email protected]") ;=> "[email protected]"
(validate-email "invalid") ;=> nil
(if (validate-email "[email protected]") :valid :invalid) ;=> :valid
(if (validate-email "invalid") :valid :invalid) ;=> :invalid

And if you need a good regexp to match emails against, see Using a regular expression to validate an email address.

like image 141
Leonid Beschastny Avatar answered Jul 11 '26 06:07

Leonid Beschastny


(defn validate-email
  [email]
  (let [pattern #"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"]
    (and (string? email) (re-matches pattern email))))

As far as regular expressions in Clojure, this might help: http://www.lispcast.com/clojure-regex


Or, funcool/struct can be used to validate email, beside other things.

like image 23
Marcin Bilski Avatar answered Jul 11 '26 06:07

Marcin Bilski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!