Pages

Tuesday 1 April 2014

Javascript validations for invalid characters in the textarea.



 Once clicks on a submit button , java script validations checks whether the text area contains valid characters or not.  If text area contains invalid characters like ^?'"~`\<>  then form will not submit. Other wise it will submit.

Sourcecode:

<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>

<html>
    <head>
    <title>Textarea validations</title>
<script type="text/javascript">
 function validate(){
  if(document.getElementById("tarea").value==""){
   alert("Text should not be empty");
   document.getElementById('tarea').focus();
   return false;
  }

 if(document.getElementById("tarea").value!=""){
 var s=document.getElementById("tarea").value;
 //add text will not accept special charecters like  ^?'"~`\<>
 var alpha = "1234567890" +
                "abcdefghijklmnopqrstuvwxyz" +
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
                "-_@. !:#=+%$&*(){}[],|/";
            var invalid = false;
            var ch="";
            for (i=0; i < s.length; i++) {
                ch=s.charAt(i);
                //alert(alpha.indexOf(ch));
                if (alpha.indexOf(ch) < 0) {
                    invalid = true;
                    alert("not valid text");
                    break;
                }
            }
    return !invalid;
 }
   else{
    return true;
   }
 }
</script>
<script type="text/javascript">
function setFocus(tarea){
document.getElementById(tarea).focus();
return true;
}
</script>
    </head>
    <body onload ="return setFocus('tarea')">
    <div id="results1" style="position: absolute;z-index: 0;width:280px;height:200px;left:360px;top:20px;align:center;text-color:
    #036A71;"><h2><font color="#036A71"><b>Add Type Text</b></font></h2></div>
    <div id="results1" style="position: absolute;z-index: 0;width:100px;height:240px;left:10px;top:140px;align:center;text-color:
    #036A71;">
    <html:form action="/addText">
        <table>
        <tr>
        <td align ="center"><font color="#036A71" size="3"><b>Enter the text :</b></font></td>
        <td><html:textarea property="text" rows="8" cols="90" styleId="tarea"></html:textarea></td>
        </tr>
            <tr><td></td>
        <td colspan="2" align ="center"><html:submit onclick="return validate()"/></td>
        </tr>
        </table>
             <br>
    </html:form>
    </div>
  </body>
</html>

No comments:

Post a Comment