Badger
Badger

Reputation: 301

Having difficulty validating textarea input

I have a form with the target="_blank", and onsubmit="return validateForm()", as well as a textarea named "wordList". Here is my validateForm() function

    function validateForm() {
        var x = document.forms["form1"]["wordList"].value;
        if (x == null || x == "") {
            alert("Word list cannot be empty.");
            return false;
        }
    }

This works fine to test for an empty input, however I need to also verify that the wordList has a minimum number of lines of text. I have tried inserting a php block after this if statement, but by calling 'explode()', it ends up opening a new tab regardless of if there is input or not. Here's what I mean:

    function validateForm() {
        var x = document.forms["form1"]["wordList"].value;
        if (x == null || x == "") {
            alert("Word list cannot be empty.");
            return false;
        }
        <?php
        $wordInput = explode("\n", str_replace("\r", "", $_POST['wordList']));
        ?>
    }

I'm not sure how to reference the wordList in the php block when it's on the same page, but either way, whenever I click a submit button, even with an empty textarea, it opens the current page in another tab.

Is there a better way than using php to count and validate the number of lines in the text area?

Upvotes: 0

Views: 128

Answers (3)

A. Ilazi
A. Ilazi

Reputation: 341

You have to use JavaScript for this purpose. You need to find out how many linebreaks the textarea have. Here a reference to a similiar question.

enteredText = textareaVariableName.val(); numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;

Then you have to prevent the action caused by pressing the submit button with JS if the number of linebreaks doesnt match your criteria.

Here a question for handling this.

Upvotes: 1

Naga Sai A
Naga Sai A

Reputation: 10975

        var text = $("#wordList").val();   
        var lines = text.split(/\r|\r\n|\n/);
        var count = lines.length;
        console.log(count); // Outputs 4

Use it in you if condition to check countLines more than 2 var text = $("#wordList").val();
var lines = text.split(/\r|\r\n|\n/); var count = lines.length; console.log(count); // Outputs 4

          var countLines = document.getElementById("wordList").rows;

Codepen URL for reference - http://codepen.io/nagasai/pen/gMrpre

Upvotes: 1

Parag Bhayani
Parag Bhayani

Reputation: 3330

It is because php code executes at server side not client side, so you need to write javascript alternative code instead of php code ...

Here regardless of what you write in php code it won't return true or false and you want get wordList ... so it will submit the form from the client side

Upvotes: 2

Related Questions