Trying to Validate Url Using JavaScript

Check if a JavaScript string is a URL

A related question with an answer

Or this Regexp from Devshed:

function validURL(str) {
var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
return !!pattern.test(str);
}

JS Regex url validation

I change the function to Match + make a change here with the slashes and its work: (http(s)?://.)

The fixed function:

function isUrlValid(userInput) {
var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
if(res == null)
return false;
else
return true;
}

Is there a definitive solution for using jQuery to validate a URL without a plugin?

In short: No, because that's not the purpose of the Jquery library (as @Juhana mentioned).

Also, as @Adeneo wrote, clientside validation is for ui purposes only (i.e. telling the user if it's potentially valid or not). Real validation should be serverside.

That said, I recommend using this regex, which is good for ui purposes.

Validating a URL in Node.js

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



Related Topics



Leave a reply



Submit