How to properly validate a lightning address
If you are building some kind of form in your app where you ask your users to input their lightning address, then you can do a few things to validate whether what they entered is a valid address or not.
The first thing obviously is to validate that the string has the same structure as an email string.
& for that you can use any a regex, or better yet, use some built-in method from the validation library you are using.
But validating the structure alone isn't enough...
What if the user write a normal email address??
or what if he mistypes his lightning address??
So for that, we can do an extra step, which is to make an http request to the lightning address provider.
The url that we are going to make the request for is:
https://${domain}/.well-known/lnurlp/${username}
Where username
is the part before the @ in the lightning address, & domain
is the part after the @.
If the lightning address is valid, then the request to this URL should return with a status code of 200 & a json response body that contains a callback
field.
Now we can probably stop here, however...
If you do this validation on the client side, you might notice that sometimes a specific lightning address will be marked invalid even though it is valid.
The reason for that is CORS headers.
Not all lightning addresses providers put CORS headers on the response returned by them, so to solve this issue:
You can either move this validation to be done through your server api.
Or, you can use a CORS proxy (existing one or setup your own), and send your requests through this proxy.
For example the one we are using in Bolt🔩Fun is: https://codetabs.com/cors-proxy/cors-proxy.html
It has of course some limitations on the number of requests, but it should be good enough.
One final thing to note though, you shouldn't make this request on each key stroke by the user, instead you should probably debounce it a little bit for better performance.
Hopefully this was helpful,
Have a nice day.