简体   繁体   中英

How do I validate a textarea? It may not be empty

I need to add a validation to my textarea. It may not have less than, for instance, 5 characters. It needs to happen real time, and when it is empty, or below 5 chars, it should display an errormessage beneath.

HTML

<label for="meddelande"></label>
<textarea name="meddelande" id="meddelande" cols="30" rows="10" placeholder="Ditt meddelande..."></textarea>
<p>Skriv gärna något!</p>

I'm stuck. I got it to work for using regEx as validation and a guide on YT. But I guess my knowledge to turn that validation into one for is beyond me (for now...)

 const textarea = document.querySelector('#meddelande'); textarea.addEventListener('keydown', event => { const error = document.querySelector('#error'); error.style.display = event.target.value.length >= 4 ? "none" : "block"; });
 <label for="meddelande"></label> <textarea name="meddelande" id="meddelande" cols="30" rows="10" placeholder="Ditt meddelande..."></textarea> <p class="notice">Skriv gärna något!</p> <p id="error">Type at least 5 characters</p>

You can listen for the keydown press within Javascript to achieve this.

 <label for="meddelande"></label> <textarea name="meddelande" id="meddelande" cols="30" rows="10" placeholder="Ditt meddelande..."></textarea> <p class="notice">Skriv gärna något!</p> <script> const noticeElement = document.querySelector('.notice'); const textarea = document.querySelector('#meddelande'); textarea.addEventListener('keydown', validate); function validate() { if (this.value < 5) { return noticeElement.style.display = "block"; } return noticeElement.style.display = "none"; } </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM