简单表单提交之前的校验和图片验证码

 

<!---------------------测试页面test.jsp----------------------->

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<html>
<%
    String contextPath = request.getContextPath();
%>
<script src="<%=contextPath %>/js/validateRequired.js" language="JavaScript"></script>
<script src="<%=contextPath %>/js/validateMaxLength.js" language="JavaScript"></script>
<script src="<%=contextPath %>/js/validator.js" language="JavaScript"></script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试</title>
</head>
<body >
    <div>
    <form name="feedbackForm" method="post" action="test.jsp">
        <tr>
            <th>姓名</th>
            <td>
            <input type="text" name="fb_name" size/>
            </td>
        </tr>
        <tr>
            <th>问题</th>
            <td>
            <textarea id="content" name="fb_content"></textarea>(限50字)
            </td>
        </tr>
        <tr>
            <th>图形验证码</th>
            <td>
            <a><img id="codeimgId" border=0 src="jsp/image.jsp" οnclick="vimag()"/></a>
            </td>
        </tr>
        <tr>
            <td>
                <input type="button" value="提交" οnclick="javascript:feedbackSubmit();"/>
            </td>
            
        </tr>
    </form>
    </div>
</body>
<script type="text/javascript">
    //提交
    function feedbackSubmit(){
        /* var fuc = new Function("a","b","alert(a+b)");
        var i = fuc(1,2);
        alert(i);
        var str = "ss";
        var reg = Validator.Chinese;
        alert(reg);
        if(reg.test(str)){
            alert("true");
        }else{
            alert("false");
        }  */
        if(validate(document.feedbackForm)){
            alert("111");
            document.feedbackForm.submit();
        }
    }
    //校验函数
    function validate(form){
        var formValidationResult;
        formValidationResult = validateRequired(form)&&validateMaxLength(form);
        return (formValidationResult == 1);
    }
    
    function feedbackForm_required(){
        this.a0 = new Array("fb_name","姓名是必填项",new Function("varName","this.maxlength='30';return this[varName];"));
        this.a1 = new Array("fb_content","问题是必填项",new Function("varName","this.maxlength='30';return this[varName];"));
    }
    
    function feedbackForm_maxlength(){
        this.a0 = new Array("fb_name","姓名长度不能超过十个字符",new Function("varName","this.maxlength='10';return this[varName];"));
        this.a1 = new Array("fb_content","问题长度不能超过十个字符",new Function("varName","this.maxlength='10';return this[varName];"));
    }
    
    function vimag(){
        var img = document.feedbackForm.codeimgId;
        img.setAttribute("src","jsp/image.jsp?random="+Math.random());
    }
</script>

</html>



<!--图片验证码image.jsp-->

<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>

<%!
    Color getRandColor(int fc,int bc){//给定范围获取随机颜色
        
        Random random = new Random();
        
        if(fc>255) fc = 255;
        
        if(bc>255) bc = 255;
        
        int r = fc+random.nextInt(bc-fc);
        
        int g = fc+random.nextInt(bc-fc);
        
        int b = fc+random.nextInt(bc-fc);
        
        return new Color(r,g,b);
    
}
%>
<%
    //设置页面不缓存
    response.setHeader("Pragma","No-cache");

    response.setHeader("Cache-Control","no-cache");
    
    response.setDateHeader("Expires",0);
    
    //在内存中创建图像
    int width =60,height=20;
    
    BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
    
    //获取图形上下文
    Graphics g = image.getGraphics();
    
    //生成随机类
    Random random = new Random();
    
    //设定背景色
    
    g.setColor(getRandColor(200,250));
    g.fillRect(0, 0, width, height);
    
    //设定字体
    g.setFont(new Font("Times New Roman",Font.PLAIN,18));
    
    //画边框
    //g.setColor(new Color());
    //g.drawRct(0,0,width-1,height-1);
    
    //随机残成155条干扰线,使图像中的认证码不易被其它程序探测到
    g.setColor(getRandColor(160,200));
    for(int i=0;i<155;i++){

        int x = random.nextInt(width);
        int y = random.nextInt(height);
        
        int x1 = random.nextInt(12);
        
        int y1 = random.nextInt(12);
        
        g.drawLine(x,y,x+x1,y+y1);
        
    }
    
    //取随机产生的认证码(4位数)
    String sRand = "";
    for(int i=0;i<4;i++){
        String rand = String.valueOf(random.nextInt(10));
        
        sRand+= rand;
        
        //将认证码显示到图像中
        
        g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
        
        g.drawString(rand,13*i+6,16);
    }
    
    
    //认证码存入session
    session.setAttribute("random",sRand);
    
    //图像生效
    
    g.dispose();
    
    //输出图像到页面
    
    ImageIO.write(image,"JPEG",response.getOutputStream());
    
%>


<!--验证必填项validateRequired.js-->

    /**
    *      Check to see if fields must contain a value
    *   Fields are not checked if they are disabled
    *   @param form The form validation is taking place on.
    */

    function validateRequired(form){
        var isValid = true;
        var focusField = null;
        var i = 0;
        var fields = new Array();
        var formName = form.getAttributeNode("name");
        
        oRequired = eval('new '+formName.value+'_required()');
        
        for(x in oRequired){
            var field = form[oRequired[x][0]];
            if((field.type == 'hidden' ||
                field.type == 'text' ||
                field.type == 'textarea' ||
                field.type == 'file' ||
                field.type == 'checkbox'||
                field.type == 'select-one'||
                field.type == 'password')&&
                field.disabled == false){
                
                var value = '';
                //get field's value
                if(field.type == "select-one"){
                    var si = field.selectedIndex;
                    if(si>0){
                        value = field.options[si].value;
                    }
                }else if(field.type == 'chekcbox'){
                    if(field.checked){
                        value = field.value;
                    }
                }else{
                    value = field.value;
                }
                
                if(trim(value).length == 0){
                    if(i == 0){
                        focusField = field;
                    }
                    fields[i++] = oRequired[x][1];
                    isValid = false;
                }
            }else if(field.type == 'select-multiple'){
                var numOptions = field.options.length;
                lastSelected = -1;
                for(loop=numOptions-1;loop>=0;loop--){
                    if(field.options[loop].selected){
                        lastSelected = loop;
                        value = field.options[loop].value;
                        break;
                    }
                }
                if(lastSelected <0 || trim(value).length == 0){
                    if(i==0){
                        focusField = field;
                    }
                    fields[i++] = oRequired[x][1];
                    isValid = false;
                }
            }else if((field.length >0)&&(field[0].type == 'radio' || field[0].type == 'checkbox')){
                isChecked = -1;
                for(loop=0;loop<field.length;loop++){
                    if(field[loop].checked){
                        isChecked = loop;
                        break;//only one needs to be checked
                    }
                }
                if(isChecked <0){
                    if(i==0){
                        focusField = field[0];
                    }
                    fields[i++] = oRequired[x][1];
                    isValid = false;
                }
            }
        }
        if(fields.length>0){
            focusField.focus();
            alert(fields.join('\n'));
        }
        return isValid;
    }
    //Trim whitespace from left and right sides of s
    function trim(s){
        return s.replace(/^\s*/,"").replace(/\s*$/,"");
    }



<!--        验证字数限制validateMaxLength.js-->

/**
 * A field is considered valid if less than the specified maximum
 * Fields are not checked if they are disabled
 */


    function validateMaxLength(form){
        var valid = true;
        var focusField = null;
        var i = 0;
        var fields = new Array();
        var formName = form.getAttributeNode("name");
        
        oMaxLength = eval('new ' + formName.value + '_maxlength()');
        for(tmp in oMaxLength){
            var field = form[oMaxLength[tmp][0]];
            
            if((field.type == 'hidden'||
                field.type == 'text'||
                field.type == 'password'||
                field.type == 'textarea')&&
                field.disabled == false){
                
                var iMax = parseInt(oMaxLength[tmp][2]("maxlength"));
                alert("iMax"+iMax);
                var text = field.value;
                if(field.type == 'textarea'&&field.disabled==false){
                    text == text.replace(/\r\n/gi,"");
                }
                
                var length = dataLength(text);
                alert(length);
                if(length > iMax){
                    if(i == 0){
                        focusField = field;
                    }
                    alert(tmp);
                    fields[i++] = oMaxLength[tmp][1];
                    isValid = false;
                }
            }
        }
        if(fields.length>0){
            focusField.focus();
            alert(fields.join('\n'));
        }
        return isValid;
    }
    
    function dataLength(fData){
        var intLength = 0;
        for(var i=0;i<fData.length;i++){
            if((fData.charCodeAt(i)<0)||(fData.charCodeAt(i)>255))
                intLength = intLength + 2;
            else
                intLength = intLength + 1;
        }
        return intLength;
    }

image.jsp在session存了验证码,提交之后可自行先验证

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值