메뉴 건너뛰기

Dev tips

JavaScript 아이피 형식 체크 함수

taknim 2011.03.11 23:28 조회 수 : 6586 추천:1581

http://blog.naver.com/ospace99/70045324718<script>
function validateIP(value)
{
    var iplength = (value.split(/\./)).length;

    if( iplength == 4 ){
        if (value.search(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) != -1) { // ip 4
            var myArray = value.split(/\./);
            if (parseInt(myArray[0],10) > 255 || parseInt(myArray[1],10) > 255 || parseInt(myArray[2],10) > 255 || parseInt(myArray[3],10) > 255){
                return false;
            }

            if ( parseInt(myArray[0],10) == 0 && parseInt(myArray[1],10) == 0 && parseInt(myArray[2],10) == 0 && parseInt(myArray[3],10) == 0){
                return false;
            }

            return true;
        } else {
            return false;
        }
    } else if( iplength == 6 ){
        if (value.search(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}.\d{1,3}$/) != -1) { // ip 6
            var myArray2 = value.split(/\./);
            alert(myArray2);
            if (parseInt(myArray2[0],10) > 255 || parseInt(myArray2[1],10) > 255 || parseInt(myArray2[2],10) > 255 || parseInt(myArray2[3],10) > 255 || parseInt(myArray2[4],10) > 255 || parseInt(myArray2[5],10) > 255){
                return false;
            }

            if ( parseInt(myArray2[0],10) == 0 && parseInt(myArray2[1],10) == 0 && parseInt(myArray[2],10) == 0 && parseInt(myArray2[3],10) == 0 && parseInt(myArray2[4],10) == 0 && parseInt(myArray2[5],10) == 0){
                return false;
            }

            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}


alert(validateIP("221.221.221.221")); // true
alert(validateIP("221.221.221.221.225.255.15")); //false
</script>