I\'m trying to validate the content of a using JavaScript, So I created a
validate()
function, which returns
I have been using this pattern for awhile, and seems to be working for your case, too:
/^[a-zA-Z0-9][a-zA-Z0-9\-_]*\.([a-zA-Z0-9]+|[a-zA-Z0-9\-_]+\.[a-zA-Z]+)+$/gi
The logic is simple:
^[a-zA-Z0-9]
: The URL must start with an alphanumeric character[a-zA-Z0-9\-_]*
: The first alphanumeric character can be followed by zero or more of: an alphanumeric character, an underscore or a dash\.
: The first piece must be followed by a period.[a-zA-Z0-9]+
: One or more alphanumeric character, OR[a-zA-Z0-9\-_]+\.[a-zA-Z0-9]+
: One or more alphanumeric character, an underscore or a dash followed by a period and one or more alphanumeric characterYou can check this pattern working for most of your URLs in the following code snippet. How I do it is similar to the strategy described by others:
,
character$.trim()
to remove flanking whitespacesOptional, done for visual output:
$(function() {
$('textarea').keyup(function() {
var urls = $(this).val().split(',');
$('ul').empty();
$.each(urls, function(i,v) {
// Trim URL
var url = $.trim(v);
// RegEx
var pat = /^[a-zA-Z0-9][a-zA-Z0-9\-_]*\.([a-zA-Z0-9]+|[a-zA-Z0-9\-_]+\.[a-zA-Z]+)+$/gi,
test = pat.test(url);
// Append
$('ul').append('- '+url+' '+test+'
');
});
});
});
textarea {
width: 100%;
height: 100px;
}
ul span {
background-color: #eee;
display: inline-block;
margin-left: .25em;
padding: 0 .25em;
text-transform: uppercase;
}