我编写了一个用于验证JSp页面的代码。但特殊字符验证不起作用。有人可以告诉我原因。如果我的方法有误,请用正确的方法通知我。
JSP代码
<%--
Document : LapsePeriodicFeedBack
Created on : Dec 7, 2012, 2:50:28 PM
Author : Admin
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.util.*" %>
<%@page import="PeriodicFeedBack.PeriodicType"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LapsePeriodicList</title>
<style>
body {
font: 11px Arial, Helvetica, sans-serif;
background-color:#E4Eff4;
padding: 0;
margin: 10px;
}
</style>
<script>
function validateForm(){
var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
var selectindex=document.forms["lapse"]["periodmenu"].selectedIndex;
var whitespace = /\w+/g;
var x= document.forms["lapse"]["lapsedays"].value;
var textlength=document.forms["lapse"]["lapsedays"].length;
if(x==""){
alert("Days Cant Be Empty");
return false;
}
if(!whitespace.test(x)){
alert("White Spaces are not Allowed");
return false;
}
if(selectindex==0){
alert("Please select Days from menu");
}
if(isNaN(x)){
alert("Only Numbers Allowed");
return false;
}
if(x.indexOf(iChars) != -1) {
alert ("The box has special characters. \nThese are not allowed.\n");
return false;
}
}
</script>
</head>
<body>
<form method="post" name="lapse" onsubmit="return validateForm()" action="LapsePeriodicFbUpdate">
<table width="450px" border="1" align="center" style='border-collapse: collapse;font: 13px Arial, Helvetica, sans-serif;' bordercolor='#000000'>
<tr style="color:'#ffffff';background-color:#CA1619;background-repeat:repeat-x;font: 13px Arial, Helvetica, sans-serif;">
<td colspan="4" align="center">
<font color="#ffffff" > <b>Periodic Feedback List</b></font></td></tr>
<tr >
<td align="center">
Periodic Feedback Days</td>
<td align="center">
<select id="periodmenu" STYLE="width: 150px" name="periodmenu">
<option>Select</option>
<%
PeriodicType p = new PeriodicType();
ArrayList periodicList = p.getPeriodicType();
for (int i = 0; i < periodicList.size(); i++) {%>
<option value="<%=periodicList.get(i)%>">
<% out.println(periodicList.get(i));
}%>
</option>
</select></td>
</tr>
<tr>
<td align="center">
Lapse Days </td>
<td align="center">
<input id="lapsedays" name="lapsedays" onkeyup="nospaces(this)" style="width:145px;" type="text" />
</td>
</tr>
<tr>
<td align="right" colspan="2"><input type="submit" id="submit" value="Submit"/></td>
</tr>
</table>
</form>
<p>
</p>
</body>
</html>
答案 0 :(得分:1)
x.indexOf(iChars)
行与x
字符串匹配iChars
字符串。
您可以使用正则表达式搜索,如下所示:
var iChars = "[!@#$%^&*()+=\\-\\[\\]\\\';,./{}|\":<>?]{1}";
....
if(x.search(iChars) != -1)
....