應用了簡單的正則表達式,代碼如下(包含了一個replace單獨的效果button)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表單空白驗證</title>
<script>
window.οnlοad=function(){
var _isContent=document.getElementById("isContent"),
_rstrs=document.getElementById("rstrs"),
_strs=document.getElementById("strs");
_rstrs.οnclick=function(){
_strs.value=_strs.value.replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g,"");
}
_isContent.οnclick=function(){
if(_strs.value.replace(/^(\s|u00A0)+|(\s|u00A0)+$/g,""))
{
alert("非空");
}else{
alert("空");
}
}
};
</script>
</head>
<body>
<label for="strs">請輸入</label><br/>
<input type="text" id="strs" value=" 需要驗證空格"/>
<input type="button" id="rstrs" value="過濾"/><br/>
<input type="button" id="isContent" value="驗證是否爲空" />
</body>
</html>