I've already posted an article on how to validate forms with Regular Expression. But, have you ever needed to valid an URL?
We can do it quite easily using Regular Expressions and JavaScript. Specifically we are going to use the .test method.
The code
The first thing we need to do is set two variables: one is the URL to be validated, the second is the Regular Expression.
<script type="text/javascript">
var url = "http://www.google.com/";
var urlCheck = /^http:\/\/(www\.)?[a-zA-Z0-9-]{3,}\.[a-zA-Z]{2,}(\/)?$/;
Now we can check the url using a snippet like:
if (urlCheck.test(url) == false)
{
alert("URL is not correct!");
}
else
{
alert("URL correct!");
}
</script>
According to the URL specified in the url variable, we will receive an alert message: if the url is correct or not.Now, remember that the above is just an example to show the .test method. Depending on the if clause, we can create different results. For example in a form we can be sure that the submitted url is a valid one and not a fake one. Or anything else.
Nice and easy.
Enjoy yourself, and take care.
Oh! By the way, don't you think it's time to drop a line? So, just use the comments section below!
0 thoughts:
Post a Comment
Comments are moderated. I apologize if I don't publish comments immediately.
However, I do answer to all the comments.