How to use regular expression in input?

Asked

Viewed 672 times

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

  • 5

    Your first example eliminates everything that is not an input number while the user types. It’s not exactly good practice, but it’s doable. However, I don’t see how this could be applied to a URL - because to enter a valid URL (eg.: http://google.com) you will necessarily pass for an invalid (e.g..: h, ht, htt, http, http: etc). I suggest not validating onkeyup, but somewhere else; preferably after the user has finished typing (eg.: onblur field or onsubmit form)

  • 2

    The validation code in this case is really not trivial. I suggest taking a look at plugins like the jQuery Validaiton. See the example for Urls, it makes a first validation when losing focus and then validates each edition.

  • Very good is more complex and meets what I need

  • @Anthonyaccioly Great suggestion, in this case although the "validation" is made at each edition, it does not altering user input: only says whether it is valid or not. And this is a good behavior, from the point of view of usability (a while ago I did a question in Soen similar to that, and also I was advised not to change the input while the user typed).

  • @Anthonyaccioly Sure, why not? Feel free to use the content of my first comment and/or linked response in the second, if it helps make it a real answer.

1 answer

2

In accordance with comment from mgibsonbr, "masks" for URL are not a good idea. A better strategy is to validate the URL after loss of focus with some kind of visual indication.

As this kind of validation strategy is not trivial I suggest using one of the many libraries for validation. In particular I can recommend the library jQuery validation who owns 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 is 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
    }
  }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.