Home > Software engineering >  What is the regex for url validation in react native?
What is the regex for url validation in react native?

Time:11-23

URL validation checks if a given text is a URL or not. Such checks are often performed when a user has to enter a URL on a web form. To ensure that the entered text corresponds to a URL, I tried to implement the regex like this

regexurl = “((http|https)://)(www.)?”   “[a-zA-Z0-9@:%._\\ ~#?&//=]{2,256}\\.[a-z]”   “{2,6}\\b([-a-zA-Z0-9@:%._\\ ~#?&//=]*)”

But I am getting error, Please help where I am being wrong Thanks in advance

CodePudding user response:

If your runtime supports it, the better way of validating URLs is using the URL constructor. You can then use the parsed object to verify parts of it separately. For example, to check if something is a valid HTTP(s) URL:

function isValidHttpUrl(s) {
  let url;
  try {
    url = new URL(s);
  } catch (e) { return false; }
  return /https?/.test(url.protocol);
}

isValidHttpUrl("banana"); // false, not a URL
isValidHttpUrl("http://example.com"); // true, is an HTTP URL
isValidHttpUrl("ftp://example.com"); // false, despite being a proper URL

CodePudding user response:

Regex for URL validation:

let Regex = /[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\ ~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\ .~#?&//=]*)/

console.log(Regex.test("http://google.com")) 

Description: if the given URL is correct then it will log true else false.

CodePudding user response:

you should use this,

var expression = /[-a-zA-Z0-9@:%._\ ~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\ .~#?&//=]*)?/gi;

It resolves your issue.

  • Related