0

Is it real to set input pattern to all as usually, but with one exception: url are not acceptable. I mean for example all input patterns are ok, but:

ftp://example.com
http://example.com
https://example.com

we could not enter...

is it real to do without using javascript or no ?

Cœur
  • 32,421
  • 21
  • 173
  • 232
brabertaser19
  • 5,384
  • 14
  • 69
  • 164

3 Answers3

2

With JavaScript and using the regex found here: What is the best regular expression to check if a string is a valid URL?, you could do something like this:

function isValid(inputVal){
    return !/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/.test(inputVal);

}

isValid(document.getElementById("inputID").value);

EDIT

Without JavaScript you can do it like such

<input pattern="^(?!((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?))" >

^ # start of the string (?! # start negative look-ahead .* # zero or more characters of any kind (except line terminators) foobar # foobar )

Community
  • 1
  • 1
winhowes
  • 6,741
  • 5
  • 27
  • 39
1
  1. Choose the URL validation regex from internet ( or write your own :) ).
  2. Put it in negative look-ahead (?!).
  3. Add .* for match everything else.
  4. Use your new regex in pattern attribute of the inputs.

For example if the URL validation regex is ^(((https?)|(ftp)):\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$ the inputs will be like

<input type="text" pattern="^(?!(((https?)|(ftp)):\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?).*$" />

Note: not every regex will work if you add it in negative look-ahead so just use JavaScript and inverse the result of the original regex. Also your input must be inside a form to trigger the patern validation (on form submit).

Viktor Bahtev
  • 4,568
  • 2
  • 27
  • 37
0

The question indicates you already know the regex and just want to know whether you should be using Javascript (or HTML) for this. The answer would be: probably not.

If you are filtering input for - say - a forum, using Javascript would be a bad idea because it runs locally, so the user can easily avoid the check. Use a server-sided language (most-probably PHP) to do the check.

Stephan Bijzitter
  • 3,965
  • 3
  • 20
  • 42