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
}
}
});
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 validatingonkeyup
, but somewhere else; preferably after the user has finished typing (eg.:onblur
field oronsubmit
form)– mgibsonbr
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.
– Anthony Accioly
Very good is more complex and meets what I need
– Rose
@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).
– mgibsonbr
@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.
– mgibsonbr