Sử dụng validator.js
ES6
import isURL from 'validator/lib/isURL'
isURL(string)
Không có ES6
var validator = require('validator');
validator.isURL(string)
Bạn cũng có thể tinh chỉnh hành vi của chức năng này bằng cách chuyển optionsđối tượng tùy chọn làm đối số thứ hai củaisURL
Đây là optionsđối tượng mặc định :
let options = {
protocols: [
'http',
'https',
'ftp'
],
require_tld: true,
require_protocol: false,
require_host: true,
require_valid_protocol: true,
allow_underscores: false,
host_whitelist: false,
host_blacklist: false,
allow_trailing_dot: false,
allow_protocol_relative_urls: false,
disallow_auth: false
}
isURL(string, options)
host_whitelistvà host_blacklistcó thể là mảng của máy chủ. Họ cũng hỗ trợ các biểu thức thường xuyên.
let options = {
host_blacklist: ['foo.com', 'bar.com'],
}
isURL('http://foobar.com', options) // => true
isURL('http://foo.bar.com/', options) // => true
isURL('http://qux.com', options) // => true
isURL('http://bar.com/', options) // => false
isURL('http://foo.com/', options) // => false
options = {
host_blacklist: ['bar.com', 'foo.com', /\.foo\.com$/],
}
isURL('http://foobar.com', options) // => true
isURL('http://foo.bar.com/', options) // => true
isURL('http://qux.com', options) // => true
isURL('http://bar.com/', options) // => false
isURL('http://foo.com/', options) // => false
isURL('http://images.foo.com/', options) // => false
isURL('http://cdn.foo.com/', options) // => false
isURL('http://a.b.c.foo.com/', options) // => false
http, nó là mặc định không có url.