Simple server-side form validation from our Android phone

Simple server-side form validation from our Android phone

Introduction

In this tutorial, we will be learning how to validate users' data on the server side using the PHP programming language that was installed on our Android device. You can also follow through using your laptop/system, just want to show how possible it is to create a PHP script directly from your Android device.

Prerequisites

Before we begin this tutorial, a few things are expected of you the reader:

  1. Have access to an Android device.

  2. Has Termux installed on your Android device, to learn how to install Termux, read here.

  3. Have PHP installed through Termux on your Android device, you can also learn it here

  4. Basic knowledge of HTML, CSS or Bootstrap CSS

  5. Basic knowledge of PHP is required.

  6. You need a text editor to be able to write the code in this tutorial, you can download it from Google Playstore, but for me, I'm using Acode as my text editor which I installed from F-Droid.

  7. You must have an internet connection.

Now that we have everything ready to go, open your Termux application, and let's create a root folder for our little project from there.

Once you have opened it you can type clear on the terminal and hit enter on your phone's keyboard to clear the welcome text from the screen.

Next type cd storage/shared and hit enter to change the directory from home to the ones you have on your phone.

Screenshot_20221205-141114.png

Now let's create a directory, type mkdir projectName hit enter from your phone's keyboard to create the folder. You can use any name for your folder, but in my case, I will call it form-validate.

Once you are done with that, the next step is to typecd form-validate to move into that directory so that we can create the files that we needed.

Creating files is very simple and straightforward too, still in your Termux terminal, type touch index.php, hit enter to create the file. For simplicity's sake, we will be working from this single file, we don't need a CSS file because we will be using Bootstrap CSS to style our form.

Screenshot_20221205-141941.png

HTML & Bootstrap CSS

The next step is to create the form needed to validate and open the file we created in the previous test in a code editor. Again I'm using Acode as my source code editor on my Android phone, you can also download it from Playstore or F-Droid.

Here's how my form looks like

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">

    <title>Form validation</title>
  </head>
  <body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled">Disabled</a>
      </li>
    </ul>
  </div>
</nav>
    <h3 class="mt-3 text-center mb-3">Simple Form Validation using our Android Phone</h3>
<div class="container mb-4">
<form action="" method="post">
  <div class="form-group">
    <label for="fname">First Name</label>
    <input type="text" class="form-control" name="firstname" aria-describedby="firstname">
  </div>
  <div class="form-group">
    <label for="lname">Last Name</label>
    <input type="text" class="form-control" name="lastname" aria-describedby="lasttname">
  </div>
  <div class="form-group">
    <label for="email">Email Address</label>
    <input type="email" class="form-control" name="email" aria-describedby="email">
  </div>
  <div class="form-group">
    <label for="password">Password</label>
    <input type="password" class="form-control" name="password">
  </div>
  <div class="form-group">
    <label for="cpassword">Confirm Password</label>
    <input type="password" class="form-control" name="cpassword">
  </div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
  </body>
  </html>

Because we are using .php extension, we need to serve our app so that we can see the changes that we've made so far. To serve your PHP files, in your Termux terminal, in the same directory we save our project, that's where we will serve the project from, type php -S localhost:8000, then hit enter to start the built-in server from PHP.

Screenshot_20221205-143917.png

Now open your favorite browser to see what you've done up till this moment. If you follow through, we should both have something like this ⬇️⬇️⬇️

Screenshot_20221205-145855.png

PHP scripts

Now for the main point of our project, we've created the HTML markup we needed, and now is time to validate the code.

Inside the .php file at the top, include this line of code

<?php 
$error = [];
if($_SERVER['REQUEST_METHOD'] == "POST"){
  $first_name = $_POST["firstname"];
  $last_name = $_POST['lastname'];
  $email = $_POST["email"];
  $pass = $_POST['password'];
  $cpass = $_POST["cpassword"];

  // performing validation
  if(!$first_name){
    $error['firstname'] = "First name is required";
  }
  if(!$last_name){
    $error['lastname'] = "Last name is required";
  }
  if(!$email){
    $error['email'] = "Email is required";
  }elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
    $error['email'] = "The email address you entered is invalid";
  }
  if(!$pass){
    $error['password'] = "Password is required";
  }elseif(strlen($pass) <= 4){
    $error['pass'] = "Password length should be atleast 5";
  }
  if(!$cpass){
    $error['cpassword'] = "Confirm Password is required";
  }elseif($cpass !== $pass){
    $error['cpassword'] = "Confirm password must match with password";
  }
  //  if there's no error message
  if(empty($error)){
    echo "Your First name is: " . $first_name . "<br>";
    echo "Your Last name is: " . $last_name . "<br>";
    echo "Your Email address is: " . $email . "<br>";
  }
}
?>

Explanation of Code

  1. In line 1 is the opening tag of the PHP <?php, this line is needed to tell the browser that this is a PHP script so that the server will be able to handle it correctly.

  2. line 2 I created an empty array outside of the if statement block so that we store errors there.

  3. line 3 is the if statement needed to run the validation logic. Inside the opening and closing bracket is to check if the user clicks the button and the REQUEST_METHOD is equal to POST.

  4. I stored the user's details in a variable I can reuse later using to avoid repeating the same code. I access the global $_POST['firstname'] to know what the user has entered into the form fields.

  5. Next, I write the necessary validation rules I want, if the user does not meet the required validation, the error is saved in an array $error['firstname'] variable that I can access later and show the error later.

  6. Once there's no error found, PHP will print the user's first name, last name and email address to the browser.

Showing Error messages

The code below shows how we will print out error messages to the browser

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">

    <title>Form validation</title>
  </head>
  <body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled">Disabled</a>
      </li>
    </ul>
  </div>
</nav>
    <h3 class="mt-3 text-center mb-3">Simple Form Validation using our Android Phone</h3>
<div class="container mb-4">
<form action="" method="post">
  <div class="form-group">
    <label for="fname">First Name</label>
    <input type="text" class="form-control <?php echo isset($error['firstname']) ? 'is-invalid' : ""?>" name="firstname" aria-describedby="firstname">
    <small class="invalid-feedback">
      <?= $error["firstname"] ?? "" ?>
    </small>
  </div>
  <div class="form-group">
    <label for="lname">Last Name</label>
    <input type="text" class="form-control <?php echo isset($error['lastname']) ? 'is-invalid' : ""?>" name="lastname" aria-describedby="lasttname">
<small class="invalid-feedback">
      <?= $error["lastname"] ?? "" ?>
    </small>
  </div>
  <div class="form-group">
    <label for="email">Email Address</label>
    <input type="email" class="form-control <?php echo isset($error['email']) ? 'is-invalid' : ""?>" name="email" aria-describedby="email">
<small class="invalid-feedback">
      <?= $error["email"] ?? "" ?>
    </small>
  </div>
  <div class="form-group">
    <label for="password">Password</label>
    <input type="password" class="form-control <?php echo isset($error['password']) ? 'is-invalid' : ""?>" name="password">
<small class="invalid-feedback">
      <?= $error["password"] ?? "" ?>
    </small>
  </div>
  <div class="form-group">
    <label for="cpassword">Confirm Password</label>
    <input type="password" class="form-control <?php echo isset($error['cpassword']) ? 'is-invalid' : ""?>" name="cpassword">
<small class="invalid-feedback">
      <?= $error["cpassword"] ?? "" ?>
    </small>
  </div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
  </body>
  </html>

Explanation of code

You will notice I've made some changes to the HTML files, Inside the input tags I injected PHP code inside the class div, this was done so that if there's an error, the border of the input tag will turn red, for simplicity's sake, I'm using Bootstrap CSS classes to speed things up. Next, is another tag named <small> to output the error to the user so that the user can adjust. Below is the result if the user didn't input the necessary credentials.

Screenshot_20221205-174556.png

Finally, let's help the user to remember what they typed inside the input box so that they won't have to type everything over again.

<?php 
if($_SERVER['REQUEST_METHOD'] == "POST"){
  $first_name = trim($_POST["firstname"]);
  $last_name = trim($_POST['lastname']);
  $email = trim($_POST["email"]);
  $pass = trim($_POST['password']);
  $cpass = trim($_POST["cpassword"]);

  // performing validation
  if(!$first_name){
    $error['firstname'] = "First name is required";
  }
  if(!$last_name){
    $error['lastname'] = "Last name is required";
  }
  if(!$email){
    $error['email'] = "Email is required";
  }elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
    $error['email'] = "The email address you entered is invalid";
  }
  if(!$pass){
    $error['password'] = "Password is required";
  }elseif(strlen($pass) <= 4){
    $error['password'] = "Password length should be atleast 5";
  }
  if(!$cpass){
    $error['cpassword'] = "Confirm Password is required";
  }elseif($cpass !== $pass){
    $error['cpassword'] = "Confirm password must match with password";
  }

  if(empty($error)){
    echo "Your First name is: " . $first_name . "<br>";
    echo "Your Last name is: " . $last_name . "<br>";
    echo "Your Email address is: " . $email . "<br>";
  }
}
?>
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">

    <title>Form validation</title>
  </head>
  <body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled">Disabled</a>
      </li>
    </ul>
  </div>
</nav>
    <h3 class="mt-3 text-center mb-3">Simple Form Validation using our Android Phone</h3>
<div class="container mb-4">
<form action="" method="post">
  <div class="form-group">
    <label for="fname">First Name</label>
    <input type="text" class="form-control <?php echo isset($error['firstname']) ? 'is-invalid' : ""?>" name="firstname" aria-describedby="firstname" value="<?= $first_name ?? ""?>">
    <small class="invalid-feedback">
      <?= $error["firstname"] ?? "" ?>
    </small>
  </div>
  <div class="form-group">
    <label for="lname">Last Name</label>
    <input type="text" class="form-control <?php echo isset($error['lastname']) ? 'is-invalid' : ""?>" name="lastname" aria-describedby="lasttname" value="<?= $last_name ?? ""?>">
<small class="invalid-feedback">
      <?= $error["lastname"] ?? "" ?>
    </small>
  </div>
  <div class="form-group">
    <label for="email">Email Address</label>
    <input type="email" class="form-control <?php echo isset($error['email']) ? 'is-invalid' : ""?>" name="email" aria-describedby="email" value="<?= $email ?? ""?>">
<small class="invalid-feedback">
      <?= $error["email"] ?? "" ?>
    </small>
  </div>
  <div class="form-group">
    <label for="password">Password</label>
    <input type="password" class="form-control <?php echo isset($error['password']) ? 'is-invalid' : ""?>" name="password">
<small class="invalid-feedback">
      <?= $error["password"] ?? "" ?>
    </small>
  </div>
  <div class="form-group">
    <label for="cpassword">Confirm Password</label>
    <input type="password" class="form-control <?php echo isset($error['cpassword']) ? 'is-invalid' : ""?>" name="cpassword">
<small class="invalid-feedback">
      <?= $error["cpassword"] ?? "" ?>
    </small>
  </div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
  </body>
  </html>

Conclusion

Phew, we've come to the end of the tutorial, I have successfully shown you that it is possible to create a fully functional app on your Android phone, and now you can keep learning even on your Android device.

NB: you can get the source code from my GitHub repository here.

Thanks for reading, please you can share it with others...