问题
What is a robust way (doesn't have to be regex, does it?) to validate that a URI works on Android by only using JavaScript?
That is, the check is not done in Java on the Android SDK side; it's done in a webpage using JavaScript.
EDIT: By "works on Android", I mean that Android can find an Activity that responds to an Intent using that URI.
回答1:
Javascript is never as robust as backend but there are plenty off decent regex's around.
This is covered in another post here Trying to Validate URL Using JavaScript
The best answer I think is below
Someone mentioned the Jquery Validation plugin, seems overkill if you just want to validate the url, here is the line of regex from the plugin:
return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
Here is where they got it from: http://projects.scottsplayground.com/iri/
回答2:
A good regex for URIs (which are a superset of URLs) surely is https://github.com/jhermsmeier/uri.regex. Unfortunately, it does not cover all types of URIs yet. However, it works in Chrome.
A more simpler version is available at http://jmrware.com/articles/2009/uri_regexp/URI_regex.html. Due to multiline, I could not include it here.
And here a step-by-step development with JUnit test cases: http://timezra.blogspot.de/2010/05/regex-to-validate-uris.html This doesn't work here "Invalid regular expression: Invalid group"
回答3:
Simply try calling in your code:
const url = new URL(urlToCheck)
If the given urlToCheck
or the resulting URL are not valid URLs,
then exception is thrown..... and then you know...
see:
https://javascript.info/url
https://developer.mozilla.org/en-US/docs/Web/API/URL/URL
来源:https://stackoverflow.com/questions/11528249/uri-validation-in-javascript