Objective and outcomes

In this tutorial we are going to learn validation on textarea in javascript. In this tutorial we are also going to learn to trim the whitespaces in beginning and the end of the text input. First we will check textarea for null value. And second you will notice that if you enter spaces and did not type any letter the form will still be accepted therefore we will trim the whitespaces.


HTML code:

<html>
<body>
<form name="form2" onSubmit="return(form_valid());" method="post">
<textarea name="desc" rows="3" cols="5"></textarea><br/><br/>
<input type="submit" value="submit"><br/>
</form>
</body>
</html>





Javascript:

<script>
function form_valid()
{
function trim(str) 
{ 
return str.replace(/^\s+|\s+$/g,""); 
}
	
if (trimfield(document.forms["form2"]["desc"].value) == "") 
{
alert("Please Write Problem Description");
return false;
}	
}
</script>


In the above script the trim function search the input for whitespaces in beginning and end of the string. ^\s+ expression search and remove the whitespaces from beginning while \s+$ expression search and remove the whitespaces from the end. 'g' means to search the string globally.