Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1024 How can I validate a textarea so that a maximum of 10 rows with a maximum or 60 characters per row is allowed to be submitted?

You are here: irt.org | FAQ | JavaScript | Form | 5 | Q1024 [ previous next ]

It can be done by splitting the value of the textarea on the newline character code:

<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript"><!--
var splitIndex = 0;
var splitArray = new Array();

function splits(string,text) {
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return;
    if (i == -1) {
        splitArray[splitIndex++] = string;
        return;
    }

    splitArray[splitIndex++] = string.substring(0,i);

    if (i+txtLength < strLength)
        splits(string.substring(i+txtLength,strLength),text);

    return;
}

function split(string,text) {
    splitIndex = 0;
    splits(string,text);
}

function validate() {
    split(document.myform.mytext.value,'\n');
    if (splitIndex > 10) {
        alert('Only 10 rows')
        return false;
    }
    for (var i=0;i<splitIndex;i++) {
        if (splitArray[i].length > 60) {
            alert('Only 60 cols');
            return false;
        }
    }
    return true;
}
//--></SCRIPT>

<SCRIPT LANGUAGE="JavaScript1.1"><!--
function split(string,text) {
    splitArray = string.split(text);
    splitIndex = splitArray.length;
}
//--></SCRIPT>
</HEAD>

<BODY>

<FORM NAME="myform" onSubmit="return validate()">
<TEXTAREA NAME="mytext" ROWS="5" COLS="60">
Lion
Tiger
Bear
Fox
Rabbit
Anteater
Snake
Dog
Cat
</TEXTAREA>
<P><INPUT TYPE="SUBMIT">
</FORM>

</BODY>
</HTML>

Feedback on 'Q1024 How can I validate a textarea so that a maximum of 10 rows with a maximum or 60 characters per row is allowed to be submitted?'

©2018 Martin Webb