-2

When I sanitize the input fields or text area I face a problem. When someone gave spaces and submit the form, my script accepts the form. But I want not to accept fields until there is not written at least a single character. My code is as follows.

Html

<form action="" method="POST">
    <textarea name='text'></textarea>
    <input type='submit' name='submit'>
</form>

Php

if(isset($_POST['submit'])){
    if(isset($_POST['text']) && !empty($_POST['text'])){
          //do whatever but not accept white space
    }
}
always-a-learner
  • 3,671
  • 10
  • 41
  • 81
Saqlain
  • 465
  • 3
  • 11
  • Your `!empty($_POST['text'])` should do this. I can't see this failing. Your question isn't properly written; it's actually unclear. – Funk Forty Niner Jun 17 '17 at 12:12

3 Answers3

1

You can trim whatever you want, just by using

trim()

Which removes characters from both sides of a string. Documentaion: http://php.net/manual/bg/function.trim.php

Rumen Panchev
  • 468
  • 11
  • 26
0

trim and preg_replace will do this easily

<?php
  echo $text = "  this is     niklesh       raut    ";
  echo "\n";
  $text = preg_replace('/\s+/', ' ',$text);
  echo trim($text);
?>

live demo : https://eval.in/818137

OUTPUT :

  this is     niklesh       raut    
this is niklesh raut

With new line and tab : https://eval.in/818138

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
-1

You can either echo out your statement:

<?php
   if(isset($_POST['submit'])){
    if(empty($_POST['text'])){
          echo "Please enter a value.";
    }
}

Or, add the required attribute to your input field.

<form action="" method="POST">
    <textarea name='text' required></textarea>
    <input type='submit' name='submit'>
</form>