Back to all resources
URL validation
Regular Expressions
jQuery
Event Handling

Validation - Website

By Jared Malan
This JavaScript code consists of a function validWebsite that validates URLs using a regular expression, and a jQuery event handler that triggers when an element with the #website-el loses focus.

The validWebsite function takes a single argument url and checks if it matches a specific pattern defined by a regular expression. The regular expression allows for optional protocols (http, https), optional www., followed by a domain name that can include alphanumeric characters, hyphens, and periods. The domain must end with a period followed by 2 to 5 alphabetic characters, optionally followed by a colon and port number (1 to 5 digits), and optionally followed by any path. The function returns true if the URL matches the pattern, otherwise false.

The jQuery event handler is attached to an HTML element with the ID website-el. When this element loses focus (on blur), the function retrieves the value of the element, assumed to be a URL. It then calls the valid-Website function to check if the URL is valid. If the URL is not valid, an error handling process (commented as throwing an error) should be implemented.