How to use regular expression in input?

2

I would like to put in the input onkeyup an expression using html or js an example

onkeyup='this.value=this.value.replace(/[^0-9]*/g,"")'

This only accepts numbers, I want to adapt this

/^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z0-9-!-@-#-$-%-¨-&-*-?\.]{2,4}\/?([^\s<>\#%"\,\{\}\|\\^\[\]']+)?$/

to validate url

    
asked by anonymous 18.09.2014 / 11:33

1 answer

2

As per mgibsonbr comment , URL masks are not a good idea. A better strategy is to validate the URL after losing focus with some kind of visual indication.

Since this type of validation strategy is not trivial, I suggest using one of the many libraries for validation. I especially recommend the jQuery validation library that has a method ready to treat urls. The strategy of this library is to make a first "lazy" validation when the field loses focus; if there is an error, the field will be actively validated during editing.

HTML

<form id="formulario">
   <label for="minhaurl">Minha URL: </label>
   <input id="minhaurl" name="minhaurl">
   <!--...-->
</form>

JavaScript

$("#formulario").validate({
  rules: {
    minhaurl: {
      required: true,
      url: true
    }
  }
});
    
19.09.2014 / 00:40