我想在输入数据时显示错误消息(在keyup上)

时间:2016-01-18 09:13:59

标签: javascript java spring jquery-ui

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page session="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Employee Management System</title>
<link href="CSS/style.css" rel="stylesheet" type="text/css" /> 
 <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
 <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"/>
      <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
 <link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/smoothness/jquery-ui.css" />

<script language="javascript" type="text/javascript">


function checkform(pform1){
    var str=pform1.bloodGroup.value;
    var name = pform1.employeeName.value;
    var email = pform1.email.value;
    var phone = pform1.phoneNumber.value;
    var cleanstr = phone.replace(/[\(\)\.\-\ ]/g, '');
    var err={}; 
    var DOB = pform1.dateOfBirth.value;
    var validemail =/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    var income = pform1.annualIncome.value;
    var Id = pform1.employeeId.value;
    var salary = income.replace(/[\(\)\.\-\ ]/g, '');
    var Eid = /^[a-zA-Z0-9]+$/;
    var validName = /^[a-zA-Z0-9]+$/;
    var validDOB = /^[0-9\/]+$/;

//check required fields
//password should be minimum 4 chars but not greater than 8
if (((str.length < 0) || (str.length > 3))){
err.message="Invalid blood group"; 
err.field=pform1.bloodGroup; 
}

//validate email
else if( (email != "") && !(validemail.test(email))){
err.message="Invalid email"; 
err.field=pform1.email; 

}

//check phone number
else if (isNaN((cleanstr))) { 
err.message="Invalid phone number"; 
err.field=pform1.phoneNumber; 
}

else if (isNaN((salary))) { 
    err.message="Invalid Annual Income"; 
    err.field=pform1.annualIncome; 
    }

else if((Eid == "") || !(Eid.test(Id))){
    err.message="Invalid Employee Id"; 
    err.field=pform1.employeeId;  
    }

else if((name == "") || !(validName.test(name))){

    err.message="Invalid Employee Name"; 
    err.field=pform1.employeeName; 

    }

else if( (DOB == "") || !(validDOB.test(DOB))){
    err.message="Invalid DOB"; 
    err.field=pform1.dateOfBirth; 
    }


if(err.message) 
        { 
                document.getElementById('divError').innerHTML = err.message;
                err.field.focus(); 
                return false;        

        } 
else
    {
    var permision = confirm("Are you sure to submit the details");
    if(permision)
        { 

            return true;
        }
    else{ 
        return false; }
    }
}
</script>

<script>
$(function() {
    $( "#dateOfBirth" ).datepicker({
          showOn: "button",
          buttonImage: "Pictures/calendicon.jpg" ,
          buttonImageOnly: true,
          buttonText: "Select date",
          changeMonth:true,
          changeYear:true,         
          yearRange: '1900:2100',
          numberOfMonths:[1,1],
          dateFormat: 'dd/mm/yy',
          maxDate: 0,
        });
  });


</script>
<script type="text/javascript">
    function crunchifyAjax() {
        var regnum ;
         var empID =$('#empId').val();
         if((typeof (empID)) != 'undefined' && (empID) != null && (empID.trim()!= ""))  
             { 
                regnum = $('#empId').val();  
               /*  alert(regnum); */
             } 
        else  
            {   $('#result').html('Employee Id invalid');
                 $('#result').css('color','red'); 
                $("#check").prop('disabled', true);
                return; 
            }




        var data = 'empId='
                + encodeURIComponent(regnum);

        $.ajax({
            url : 'entry.html',
            data : data,
            success : function(data) { 

                if(data == "true")
                    {
                        $('#result').html('Employee Id already exists');
                         $('#result').css('color','red'); 
                        $('#empId').val("");
                        $("#check").prop('disabled', true);
                    }               
                else
                    {           
                     $('#result').html('Valid EmployeeId ');
                     $('#result').css('color','green'); 
                        $("#check").prop('disabled', false);
                    }
            }
        });
    }
</script>

<style >
.colour{
background-color:#EBEBE4;border:1px solid #ABADB3;padding:2px 1px;


}
</style>
  <style>
img.ui-datepicker-trigger {
    width: 15px;
    height: 15px;
}

.msg{
font-family:FontAwesome;
    font-style:12px;
    background-color: #FEEFB3;
    content:'\f00c';

}
</style>


</head>
<body><center>  
<h2>Employee Management System</h2>
<form:form method="POST" action="./add.html" modelAttribute ="employee" onsubmit="return checkform(this);" >
<div id="errmsgbox">
<div id="divError"></div>
</div>
<table  border="0" cellpadding="0" cellspacing="0">
  <tr>
  <c:if test="${empty employee.employeeId}">
    <td width="14%">Employee ID<span class="mandatory" >*</span></td>
    <td width="35%"> <form:hidden path="ID" />
    <form:input path="employeeId"   onblur="crunchifyAjax();" id="empId" />  <div id="result" class = "msg"></div></td>
    </c:if>
     <c:if test="${!empty employee.employeeId}">
    <td width="14%">Employee ID</td>
    <td width="35%"> <form:hidden path="ID" />
    <form:input path="employeeId"  readonly = "true" class = "colour"/></td>
    </c:if>

    <td width="16%">Employee Name<span class="mandatory" >*</span></td>
    <td width="35%"><form:input path="employeeName"  /></td>
  </tr>
  <tr>
     <td>DOB<span class="mandatory" >*</span></td>
    <td><form:input path ="dateOfBirth"  id="dateOfBirth" readonly ="false"></form:input></td>  
    <td>Blood group </td>
    <td><form:input path="bloodGroup" /></td>
  </tr>
  <tr>
    <td>Annual Income </td>
    <td><form:input path ="annualIncome" /></td> 
    <td>Qualification</td>
    <td><form:input path ="qualification" /></td>
  </tr>

  <tr>
    <td>Pan No.</td>
    <td><form:input path="panNumber" /></td>

    <td>Phone No. </td>
    <td><form:input path="phoneNumber" maxlength="12" /></td>
  </tr>
  <tr>
    <td>Sex</td>
   <td><form:radiobutton path="sex"  value="m"/>Male 
   <form:radiobutton path="sex" value="f"/>Female</td>
    <td>Email</td>
    <td><form:input path="email" /></td>
  </tr>
<tr>
    <td>Address</td>

    <td colspan="3"><textarea name="" cols="" rows="2"></textarea></td>
  </tr>
</table>
<div>
     <input name="submit2" type="submit" title="Submit" value="Submit"  id = "check"  />
  <input type="button" name="reset_form" value="Reset" onclick="this.form.reset();"/>
     <a href="index.html"><input name="submit3" type="button" title="Reset" value="View All"/></a>
</div>
</form:form>
</center>
</body>
</html>

这是我的JSP页面。我已经完成了一次验证,它取决于提交按钮,即如果有任何验证失败但它会检查并抛出错误信息,但我希望它在飞行中,即进入自己。所以请帮助我!

2 个答案:

答案 0 :(得分:3)

将id属性提供给您的电子邮件文本字段并使用我的代码:

$(document).ready(function(){
   $("#email").keyup(function(){
     var email = $(this).val();
    // here you can validate email and show alert or show message into your error box.
        var pattern=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if(pattern.test(email)){
            $("#errmsgbox").html("Valid email address");
        }else{
            $("#errmsgbox").html("Please enter valid email address");
        }
   });
});

答案 1 :(得分:0)

您必须创建一个函数来保存该事件。

E.g var email = document.getElementById(&#39; email&#39;);

Email.onkeyup = function(){

if(email.value.length&gt; 5){

//显示错误,可能显示错误div并在其内部htlm中插入错误消息。希望你现在得到这个概念 } }

更好的是,您可以创建一个函数来运行此操作并填写参数,例如checkinput(id,lenght,errorid);