javascriptregexstringtrix

Trix validation of URL using regex


I am trying to alter the pattern of the validation to accept these starts

https://
http://
https://www.
http://www. 
www.

This is what I have now:

inputElement.pattern = '^(https:?//|http:?//|http:?//www|https:?//www|www).+$';

It accept faulty cases such as :

wwwsa.se
http://ww.

got to this point using https://github.com/basecamp/trix/issues/624


Solution

  • You can try this

    ^(?:(?:(?:https?:\/\/)?w{3})(?:[.].*|)|(?:https?:?\/\/(?!w{1,2}\.).*))$
    

    enter image description here

    Regex Demo

    const regex = /^(?:(?:(?:https?:\/\/)?w{3})(?:[.].*|)|(?:https?:?\/\/(?!w{1,2}\.).*))$/i;
    const arr = ['https://','http://','https://www.','http://www.','www.','wwwsa.se','http://ww.','http://www.','ww.','www.','www//','www.g', 'http://wix']
    
    arr.forEach(str => {
      console.log(str, '\t\t' ,regex.test(str))
    })