By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,677 Members | 1,349 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,677 IT Pros & Developers. It's quick & easy.

How to do I validate a textarea in a form in javascript

P: 17
Expand|Select|Wrap|Line Numbers
  1. <script>
  2.     function val()
  3.     {
  4.       //ifnewline found or blank raise an alert
  5.     } 
  6.    </script>
  7.    <form>  
  8.    <textarea name = "pt_text" rows = "8" cols = "8" class = "input" WRAP ></textarea>
  9.    <input type=""button" onclick="val();"
  10.     </form>
Sep 6 '19 #1
Share this Question
Share on Google+
3 Replies


gits
Expert Mod 5K+
P: 5,389
what exactly should it validate for? you can use the

indexOf-method

or

Regular Expression

for that purpose.
Sep 6 '19 #2

P: 52
try this script for textarea validation
Expand|Select|Wrap|Line Numbers
  1.  <form>  
  2.    <textarea name = "pt_text" rows = "8" cols = "8" class = "details" WRAP ></textarea>
  3.    <input type=""button" onclick="validate();"
  4.     </form>

Expand|Select|Wrap|Line Numbers
  1. <script>
  2. function validate()
  3. {
  4.      var obj1 = document.getElementById('details');
  5.          if(trimTextarea(obj1.value) == '') 
  6.          {      
  7.               alert("Please Provide Details!");
  8.               obj1.focus();
  9.               return false;       
  10.          }
  11. }
  12.  
  13. function trimTextarea(str) 
  14.     return str.replace(/^\s+|\s+$/g,''); 
  15. }
  16. </script>
Nov 5 '19 #3

gits
Expert Mod 5K+
P: 5,389
well - the OP didn't specify for what it should validate - so throwing out such code is just guesswork. besides that a much easier and much more performant way to test for an empty value in that field would make use of Javascript's typeconversion system. You would only need to check:

Expand|Select|Wrap|Line Numbers
  1. value == 0
this 'autocasts' the value to a number and it does exactly what your trimfunction does - but with much less expensive operations.

PS: you just cant put in only 0(s) here - but usually that is ok as well with the app logic.
Nov 5 '19 #4

Post your reply

Sign in to post your reply or Sign up for a free account.