---
title: "用js进行正负小数及范围判断"
author: "charles751"
date: "2010-06-30T14:56:51Z"
tags: []
categories: ["Web前端"]
slug: "js"
draft: false
lastmod: "2010-06-30T14:56:51Z"
id: 702576
url: "https://qify.iteye.com/blog/702576"
---

最近项目中遇到一个js判断：允许输入正负数、小数，并且输入值有范围限制，而且相互之间有大小比较。

 

```
function checkNumber(id){
  var eValue = document.getElementById(id).value;
  //alert(value);
					
  if (/^(\+|-)?\d+($|\.\d+$)/.test(eValue)){//数字判断
    if(id == 'West' || id == 'East'){
      //alert(value);
      if((-180 <= eValue) && (eValue <= 180)){//范围判断
        return true;
      }else{
        alert("The west/east coordinate should be in -180 to 180");
        document.getElementById(id).value="";
        document.getElementById(id).focus();
        return false;
      }
    }else if(id == 'North' || id == 'South'){
        //alert(value);					 
        if((-90 <= eValue) && (eValue <= 90)){
          return true;
        }else{
          alert("The north/south coordinate should be in -90 to 90");
          document.getElementById(id).value="";
          document.getElementById(id).focus();
          return false;
        }
      }
    }else {
      if(document.getElementById(id).value != ""){
        alert(id +" Numbers only!");
        document.getElementById(id).value="";
        return false;
    }
  }
}


<tr>
  <td class="TDstyle01" align="center">North-South:
  <input type="text" id="North-South" name="NorthSouth" style='width:80px' onBlur="checkNumber('North-South')" >
  </td>
</tr>

<tr>
<td class="TDstyle01" align="left">East-West:&nbsp;&nbsp
<input type="text" id="East-West" name="EastWest" style='width:80px' onBlur="checkNumber('East-West')">
</td>
</tr>
```