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.
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.
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With