jsbeans

jsbeans  1.0.0

jsbeans > jsbeans > Validator.ip.js (source view)
Search:
 
Filters
/*!
 * Copyright (c) 2009 Francesco Mele jsbeans@francescomele.com
 *
 * This Software is licenced under the LGPL Licence (GNU Lesser General 
 * Public License).
 * In addition to the LGPL Licence the Software is subject to the 
 * following conditions:
 * 
 * 	i	every modification must be public and comunicated to the Author
 * 	ii	every "jsbean" added to this library must be self consistent 
 * 		except for the dependence from jsbeans-x.x.x.js
 * 	iii	copyright notice and this permission notice shall be included 
 * 		in all copies or substantial portions of the Software
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
 
/**
 * Validator extensions for IP addresses
 * @for Validator
 * @namespace jsbeans
 * @static
 * */
jsbeans.Validator.ip = {
	/**
	 * Default messages for Validator.ip extension
	 * @property ip.messages
	 * @type JSON
	 * @static
	 * */
	messages: {
		en: "is not a valid IP address",
		it: "non e' un indirizzo IP valido"
	},
	/**
	 * Checks if {@param} <code class="param">input</code>'s value contains a string representing a valid IPv4 address.<br/>
	 * Note that this method uses javascript's native <code>parseInt</code> function to check each octect, so even <code>01.01.01.01</code> may result in a valid IP address.
	 * @method assertIp
	 * @param input {DOM} the input to validate
	 * @return {boolean} true if <code class="param">input</code>'s value is valid.
	 * @static
	 * */
	assertIp: function(obj) {
		var val = (obj.value || "").replace(/^\s+|\s+$/g, "");
		if (val == "") {// if empty there's no need to check
			return true;
		}
		var splitted = val.split(".");
		if (splitted.length != 4) {
			return false;
		}
		var isNumberAdmitted = function(n) {
			if (n != null && !isNaN(n)) {
				try {
					var r = parseInt(n);
					if (r >= 0 && r <= 255) {
						return true;
					}
				} 
				catch(e) {
					return false;
				}
			} 
			else {
				return false;
			}
			return false;
		};
		for (var i = 0; i < splitted.length; i++) {
			if (!isNumberAdmitted(splitted[i])) {
				return false;
			}
		}
		return true;
	}
};

Copyright © 2016 Francesco Mele. All rights reserved.