93 lines
4.0 KiB
JavaScript
Executable File
93 lines
4.0 KiB
JavaScript
Executable File
/**
|
|
* ip validator
|
|
*
|
|
* @link http://formvalidation.io/validators/ip/
|
|
* @author https://twitter.com/nghuuphuoc
|
|
* @copyright (c) 2013 - 2015 Nguyen Huu Phuoc
|
|
* @license http://formvalidation.io/license/
|
|
*/
|
|
|
|
(function(root, factory) {
|
|
|
|
"use strict";
|
|
|
|
// AMD module is defined
|
|
if (typeof define === "function" && define.amd) {
|
|
define("validator/ip", ["jquery", "base"], factory);
|
|
} else {
|
|
// planted over the root!
|
|
factory(root.jQuery, root.FormValidation);
|
|
}
|
|
|
|
}(this, function ($, FormValidation) {
|
|
FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
|
|
'en_US': {
|
|
ip: {
|
|
'default': 'Please enter a valid IP address',
|
|
ipv4: 'Please enter a valid IPv4 address',
|
|
ipv6: 'Please enter a valid IPv6 address'
|
|
}
|
|
}
|
|
});
|
|
|
|
FormValidation.Validator.ip = {
|
|
html5Attributes: {
|
|
message: 'message',
|
|
ipv4: 'ipv4',
|
|
ipv6: 'ipv6'
|
|
},
|
|
|
|
/**
|
|
* Return true if the input value is a IP address.
|
|
*
|
|
* @param {FormValidation.Base} validator The validator plugin instance
|
|
* @param {jQuery} $field Field element
|
|
* @param {Object} options Can consist of the following keys:
|
|
* - ipv4: Enable IPv4 validator, default to true
|
|
* - ipv6: Enable IPv6 validator, default to true
|
|
* - message: The invalid message
|
|
* @returns {Boolean|Object}
|
|
*/
|
|
validate: function(validator, $field, options) {
|
|
var value = validator.getFieldValue($field, 'ip');
|
|
if (value === '') {
|
|
return true;
|
|
}
|
|
options = $.extend({}, { ipv4: true, ipv6: true }, options);
|
|
|
|
var locale = validator.getLocale(),
|
|
ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
|
|
ipv6Regex = /^\s*((([0-9A-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
|
|
switch (true) {
|
|
case (options.ipv4 && !options.ipv6):
|
|
valid = ipv4Regex.test(value);
|
|
message = options.message || FormValidation.I18n[locale].ip.ipv4;
|
|
break;
|
|
|
|
case (!options.ipv4 && options.ipv6):
|
|
valid = ipv6Regex.test(value);
|
|
message = options.message || FormValidation.I18n[locale].ip.ipv6;
|
|
break;
|
|
|
|
case (options.ipv4 && options.ipv6):
|
|
/* falls through */
|
|
default:
|
|
valid = ipv4Regex.test(value) || ipv6Regex.test(value);
|
|
message = options.message || FormValidation.I18n[locale].ip['default'];
|
|
break;
|
|
}
|
|
|
|
return {
|
|
valid: valid,
|
|
message: message
|
|
};
|
|
}
|
|
};
|
|
|
|
|
|
return FormValidation.Validator.ip;
|
|
}));
|