jsp页面提交验证 onSubmit的用法

来源:互联网 发布:域名详细信息查询 编辑:程序博客网 时间:2024/04/30 06:46

在很多时候,提交页面之前都要对提交的表单数据进行验证是否满足一定的格式要求,这个时候就要用到 onSubmit 。

onSubmit用法注意事项:

1:调用的函数名不能和关键字一样。

2:调用函数时一定要加return

3:在MyEclipse中,如果这样写(<s:form action="delete" onSubmit="return check()">)编译时会报错,这个是Myeclipse的问题,不影响使用。

如果想去掉的话,请看例子之后的解决方法,但是最好不要管他,因为你改Myeclipse配置的话,再遇到类似的错误,它就不会提示,会给你带来很多不必要的麻烦。

下面请看完整例子代码:

<%@ page language="java" contentType="text/html; charset=utf-8"%><%@ taglib prefix="s" uri="/struts-tags"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript">//创建验证名字是否为空的函数,名字为validatefunction validate(){//验证是否为空if(document.getElementById("username").value == ""){document.getElementById("msg").innerText="名字不能为空"; return false;    //是空的话弹出提示信息,并返回false}else{return true;     //不为空的话返回true }}function check(){//调用validate()并判断validate函数返回的是false还是true,是false返回false,是true返回trueif(validate()){return true;}else{return  false;}}</script>  </head>    <body>    <!-- onSubmit里面一定要写上return +(函数名) --><s:form action="delete" onSubmit="return check()"><s:textfield name="username" label="UserName" id="username" onblur="validate()"/><span id="msg" style="color: red;font-size: 10"></span><s:textfield name="pwd" label="PassWord"/><s:submit/></s:form>    </body></html>


当名字为空时,单击submint按钮的效果是这样的:(页面不会跳转,也就是说表单没有提交)

当UserName不为空时,就会执行action。
解决onSubmit加return之后编译出错问题:

操作之前:

解决方法:window -->preferences -->myeclipse -->validation -->javascript validator for Js    files 把Bulid 复选框的勾去掉 就行了

如图:

操作之后:

1 0
原创粉丝点击