I want to validate a URL of the types:
www.google.com
http://www.google.com
google.com
using a single regular expression, is it achievable? If so, kindly share a solution in JavaScript.
Please note I only expect the underlying protocols to be HTTP or HTTPS. Moreover, the main question on hand is how can we map all these three patterns using one single regex expression in JavaScript? It doesn't have to check whether the page is active or not. If the value entered by the user matches any of the above listed three cases, it should return true
on the other hand if it doesn't it should return false
.
Other easy way is use Node. JS DNS module. The DNS module provides a way of performing name resolutions, and with it you can verify if the url is valid or not.
You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.
Valid URL must begin with a scheme name, e.g. https:// . URL is working starting from Edge so everything below it might not work as you expect. Make sure you check the compatibility first. – Tony T.
js file inside the helper folder as seen below: const Validator = require('validatorjs'); const validator = async (body, rules, customMessages, callback) => { const validation = new Validator(body, rules, customMessages); validation. passes(() => callback(null, true)); validation. fails(() => callback(validation.
There's a package called valid-url
var validUrl = require('valid-url'); var url = "http://bla.com" if (validUrl.isUri(url)){ console.log('Looks like an URI'); } else { console.log('Not a URI'); }
Installation:
npm install valid-url --save
If you want a simple REGEX - check this out
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