[英]Javascript Validate URL
I use the following code to validate URL in client side. 我使用以下代码在客户端验证URL。 My question is if there is a better way to do the same.. My question is not about the regex that i am using (just the overall way of writing) 我的问题是是否有更好的方法来做同样的事情。 我的问题与我正在使用的正则表达式无关(只是整体书写方式)
this.validators.myUrl = function(value) {
if (!_.isUndefined(value) && !_.isNull(value)) {
if ($.trim(value).length == 0) {
return {
isValid: true
}
} else {
return /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i.test($.trim(value)) == true ? {
isValid: true
} : {
isValid: false,
message: "Enter a valid URL"
};
}
} else {
if ($.trim(value).length == 0) {
return {
isValid: true
}
}
}
};
Why you don't want to use ready plugins/libraries? 为什么不想使用现成的插件/库?
You can have used jQuery Validation Plugin and its url
method. 您可以使用jQuery Validation Plugin及其url
方法。
All what you need is: 您需要的是:
$( "#myform" ).validate({
rules: {
field: {
required: true,
url: true
}
}
});
where myform
is id of your form. myform
是您的表单的ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.