javascript - Validating a Url in Node.js -
hi there want validate url of types www.google.com or http://www.google.com or google.com using single reguar expression,is achievable,if so, kindly share solution in javascript. please note expect underlying protocols http or https morover main question on hand how can map these 3 patterns using 1 single regex expression in javascript doesn't have check whether page active or not,if value entered user matches of above listed 3 case should return true on other hand if doesnt should return fasle.
checking if url live
this bit of hack, buy if required so, how approach it:
1st step
parse , extract domain/ip given url
- e.g. http://drive.google.com/0/23 ------> drive.google.com
this how in nodejs:
var url = require("url"); var result = url.parse('http://drive.google.com/0/23'); console.log(result.hostname); 2nd step
ping extracted domain/ip - not servers respond icmp (ping) requests due network configuration.
var ping = require ("net-ping"); var session = ping.createsession (); session.pinghost (target, function (error, target) { if (error) console.log (target + ": " + error.tostring ()); else console.log (target + ": alive"); }); - check out net-ping package
3rd step
you can perform http request url , check status code.
var request = require('request'); request('http://www.google.com', function (error, response, body) { if (!error && response.statuscode == 200) { console.log(body) // show html google homepage. } }) - it's bit risky if web-service (since can trigger actions).
- would more complicated if url requires authentication / redirection
- check out request package
there's package that!
you can use existing nodejs package called validurl
usage:
var validurl = require('valid-url'); var url = "http://bla.com" if (validurl.isuri(url)){ console.log('looks uri'); } else { console.log('not uri'); } installation:
npm install valid-url --save if still want simple regex
google friend. check out
Comments
Post a Comment