how to limit number of characters in a textarea field processing php? how to limit number of characters in a textarea field processing php? php php

how to limit number of characters in a textarea field processing php?


You can limit this by setting maxlength attribute on textarea tag like <textarea maxlength="120"></textarea> in HTML and additionally "cut" input string in PHP by substr() function.


As mentioned by s.webbandit you can use maxlength, but note that this is a new feature introduced in HTML5, as W3 Schools article about <textarea>, so "bulletproof" solution needs Javascript. So maxlength is not supported in Internet Explorer until version 10 and in Opera not at all.

Here is one approach that uses Javascript to help you out:

<script language="javascript" type="text/javascript">   function charLimit(limitField, limitCount, limitNum) {    if (limitField.value.length > limitNum) {      limitField.value = limitField.value.substring(0, limitNum);  } else {      limitCount.value = limitNum - limitField.value.length;       }    }</script>

You can then use it like this (original source):

    <textarea name="limitedtextarea" onKeyDown="charLimit(this.form.limitedtextarea,this.form.countdown,100);">    </textarea>

This should get you going.


This is a very easy way to limit the length of a text area via JavaScript.

text area field:

<input class='textField' type='text' NAME='note1' value='' onkeyup='charLimit(this, 40);'>

JavaScript function:

function charLimit(limitField, limitNum) {  if (limitField.value.length > limitNum) {   limitField.value = limitField.value.substring(0, limitNum);}}

When the user types past 40 characters it just removes them.