jsp如何利用Javascript来判断文本框输入内容是否合法?

2024-12-18 11:20:26
推荐回答(4个)
回答1:

我以前做的一个例子,给你发过来,js稍微改一下变量就可以了
js:

function checkLoginName() {
var loginName = document.myform.loginName.value;//改成你的变量
if (loginName == "" || loginName == null) {
alert('用户名不能为空!');
return false;
} else {
var url = "action.do?method=checkLoginName&loginName=" +loginName;//跳转的action
send(url);
}
}

var xmlHttp;
function createXmlHttp() {

if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("MIcrosoft.XMLHttp");
}
}

function send(url) {
createXmlHttp();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = processRequest;
xmlHttp.send(null);
}

function processRequest() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var myfont = document.getElementById("name");//这个name跟html页面的name是对应的,不用改
while (myfont.hasChildNodes()) {
myfont.removeChild(myfont.firstChild);
}
var text = document.createTextNode();
text.nodeValue = xmlHttp.responseText;
myfont.appendChild(text);
}
}

}

-----------------------------------------------------------------------------------
action:

public ActionForward checkLoginName(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {

LoginDao dao=new LoginDao();

String loginName=request.getParameter("loginName");
loginName=new String(loginName.getBytes("ISO-8859-1"),"UTF-8");
System.out.println(loginName);
int num=dao.check(loginName);
if(num==0){
response.getWriter().println("可用");
response.getWriter().flush();
}else{
response.getWriter().println("已经使用");
response.getWriter().flush();
}
return null;
}
-----------------------------------------------------------------------------------------
dao:

public int check(String loginName){
Session ss=HibernateSessionFactory.getSession();
ss.beginTransaction();
Query q=ss.createQuery("select loginName from Login where loginName='"+loginName+"'");
List list=q.list();
ss.getTransaction().commit();
ss.close();
return list.size();
}

----------------------------------------------------------------------------------------------------------------------
html:


用户名:


  

回答2:

比如你用来判断的jsp叫做check.jsp:
<%
String key = request.getParameter('key');
// check...and done~
out.println('ok');
%>
那么你在那个页面上可以用jquery的ajax来发送给check.jsp做判断:

回答3:

javascript 做客户端验证,比如是否为空,正则匹配,如果需要后台验证的(如是否唯一)需要用ajax访问后台,处理返回结果便可

回答4:

建议用Ajax,特别是jQuery