Textarea validation does not work Javascript

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

here is the code sample: HTML:

 <form id="information" name="information" action="#" method="post">   <textarea name="text" rows="10" cols="10">   </textarea>   <input type="submit" value="submit"/>   </form> 

Javascript:

 window.onload=init;   function init(){  document.getElementById('information').onsubmit=validateForm;  }   function validateForm(){   var text= document.information.text.value;   if(text==""){   alert('text area cannot be empty');  return false;  }   }

it does not work...

回答1:

The textarea has a carriage return in it (and a space), so your condition is never true. So change it to:

<textarea name="text" rows="10" cols="10"></textarea> 

However you may want to go further and stop the user entering an "empty" response (meaning nothing but white-space). Or you may just want to remove leading and trailing white-space. If so you can do this:

text = text.trim();

Now trim() I believe is relatively new (Firefox lists it as new in 3.5). A more backwards compatible version is:

text = text..replace(/^\s\s*/, '').replace(/\s\s*$/, '');

and then testing if it's empty.

Faster JavaScript Trim has a good analysis on various white-space trimming alternatives. For instance the above can be done with one regex:

text = text..replace(/^\s+|\s+$/g, '');

but

This commonly thought up approach is easily the most frequently used in JavaScript libraries today. It is generally the fastest implementation of the bunch only when working with short strings which don't include leading or trailing whitespace. This minor advantage is due in part to the initial-character discrimination optimization it triggers. While this is a relatively decent performer, it's slower than the three methods above when working with longer strings, because the top-level alternation prevents a number of optimizations which could otherwise kick in.



回答2:

You've got a carriage return in your textarea - so its value is \n or \r\n
close your tag on the same line

Edit:
You could strip the beginning and end whitespace using this function

function trim( str ) {     return str.replace( /^\s+|\s+$/g, '' ); }


回答3:

This worked for me:

function validateForm(){   var text = document.information.text.value;   if(text == " \n "){     alert("Error");     return false;   } }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!