Tag Archives: numbers

Form data validation with PHP

This tutorial explains how to validate data that has been submitted by a user in a form. We will look at the following types of data validation:

  • Check that a text field has not been left empty
  • Check only numbers have been entered
  • Check that an email address is in the correct format

We will use the empty, is_numeric, and filter_var functions for data validation in this example. Watch the video below and then scroll down to see the sample code.

Sample PHP code

Step 1: Create a PHP file (eg. form.php) and copy the following code into that file. This file will contain the form.

<html>
<head>
  <title>Form that validates data</title>
</head>
<body>
  <form action="action_handler.php" method="POST">
    <h3>Enter a postcode and email address.</h3>
    <p>Post code: <input type="text" name="postcode"></p>
    <p>Email address: <input type="text" name="email"></p>
    <p><input type="submit" value="Submit"></p>
  </form>
</body>

Step 2: Create a PHP file called action_handler.php and copy the following code into it. This file will handle the submitted form data.

<?php
  if(!empty($_POST['postcode'])){
    $postcode = $_POST['postcode'];
    if(!is_numeric($postcode)){
      $postcode = NULL; echo "Postcode must be numeric.<br/>";
    }
  }
  else{
    $postcode = NULL; echo "You must enter a postcode.<br/>";
  }

  if(!empty($_POST['email'])){
    $email = $_POST['email'];
    if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
      $email = NULL; echo "Email address is not in the correct format.";
    }
  }
  else{
    $email = NULL; echo "You must enter an email address.<br/>";
  }

  if(($postcode != NULL) && ($email != NULL)){
    echo "Email: $email<br/>Postcode: $postcode";
  }
?>

String length in PHP

This tutorial covers a few things about strings in PHP:

  • the index of strings (each character has an index number)
  • how to find the length of a string (how many characters there are in a string)
  • how to ‘loop’ through each character of a string

Although this may not seem all that useful yet, being able to find the length of a string and process each character of a string is something that will become very useful later on.

Indexing and strings

In every string, each character has what is known as an index or index number. In PHP, indexing starts from the number 0. That means that the letter B in the word “Batman” has an index of 0, the second letter “a” will have an index of 1, the third letter “t” will have an index of 2 and so on… The image below shows an example of this.

strings
A string’s index.

You might, as an example, want to find out what the third character is in a string. You could do this by using its index number eg. $mystring[2]; would return the third character in the string.

Finding the length of a string

The length of a string is how many characters are in the string. The word “Batman” has 6 letters in it so its length is 6. Letters, numbers, spaces and other characters are all counted in a string. So the string “Hello world” will have a string length of 11 because there are 10 letters and 1 space in it.

As an example, finding the length of a string might be useful if you want to check how much text was entered into a form (eg. checking that a minimum of 10 characters was used for a password, or a maximum of 160 characters were used for a tweet). The strlen() function is used to find the length of a string. Eg.  strlen(“my string”); will return the length of a string. We will look at other string functions later on.

Looping through strings

A for loop can be used to go through every single character in a string and process it. In the video example, we do this to display every letter of a string on a new line. This example might not be all that useful, but there are many other ways that a for loop can be used to process characters in a string.

Watch the video below and then scroll down to see the sample PHP code.

Sample PHP code for displaying the length of a string:

1
2
3
4
5
6
<?php
 $name = "Batman";
 $nameLength = strlen($name);
 echo $nameLength;
 }
?>

Sample PHP code for displaying the third character in a string:

1
2
3
4
5
<?php
 $name = "Batman";
 echo $name[2];
 }
?>

Sample PHP code for looping through a string:

1
2
3
4
5
6
7
<?php
 $name = "Batman";
 $nameLength = strlen($name);
 for($i=0;$i<$nameLength;$i++){
 echo $name[$i] , '</br>';
 }
?>

PHP Manual references:

Treating text input from a form as an integer or float

If you have completed the User Input with Forms tutorial, you will now know how to ask the user for text input through a form, and use that input in some way. However, if you trying collecting input from the user in the form of numbers and then try to do some logical operations on those numbers, you may run into problems.

The first problem is that any text input will be treated as a string, not an integer. So if you try to compare two numbers eg. check if the inputted number is equal to 5, JavaScript will be trying to check if a string input is equal to a number and will not be checking if an integer input is equal to a specific integer.

The video and sample code below shows an example of using parseInt() to treat text input from a textbox as an integer value. You can also use parseFloat() to parse a string as a float (real number with decimal places). The video also shows how to grab the value from a textbox by using document.getElementById(‘idname’).value so that a logical operation can happen

The example used in the video and the code below is a simple math question game. The program displays a math problem to the user. The user can enter their answer in a textbox and the page will display a message if the user gets the correct answer. Watch the video below to see how to write the code for this program.

Once you have completed the tutorial, your program should work like this:

MathGame

Here is the code for the program:

<html>
<head>
<title>Simple math game</title>
<script type="text/javascript">
var answer = 15; // this is the answer to the math question
var attempt; // the user's attempt will be stored in this variable
 
function guess(){
 attempt = document.getElementById('attempt').value;
 attempt = parseInt(attempt); // this will now treat the textbox input value as an integer
 var result = document.getElementById('result');
 
 if (attempt == answer){
 result.innerHTML = "Correct!";
 }
 else{
 result.innerHTML = "Try again.";
 }
 
}
 
</script>
</head>
<body>
 <p>What is the answer to 10+5?</p>
 <form>
 Enter your answer:<input type="text" id="attempt"/><br/>
 <input type="button" value="Submit" onclick="guess();"/>
 </form>
 <p id="result">Enter your answer in the textbox above. It must be a number only.</p>
 
 
</form>
</body>
</html>

 Next tutorial: Submitting forms

Variables and Data Types in JavaScript

In this second video from the beginners JavaScript tutorial series, you will learn how to create variables and work with strings, integers, and float data types in JavaScript.

Variables are used to store information in program such as text, numbers or true/false values. Variables are given a name and are assigned a value. To create a variable in JavaScript we use the var keyword, then specify the variable name, use the = sign to assign a value, and then specify the value to store (you can also create a variable without immediately assigning it a value). For example: var myNumber = 50;

Variable names must be unique and cannot contain spaces. They don’t begin with a number but can contain numbers. They generally begin with a lowercase letter and if the variable name contains multiple words, then they can be indicated by using camelcase (starting each new word with an uppercase letter) eg. myVariable.

Variables can store data of different types. The main types are:

  • string – text including letters, numbers and other special characters eg. “Hello world”
  • integer – whole number values eg. 5
  • float – numbers with a decimal point eg. 5.3
  • boolean – a true or false value

Watch the video below or click here to view it on YouTube.

The code snippet below shows how to declare variables in JavaScript and how to assign values to a variable. Pay attention to the //comments which explain the different ways of setting up variables.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Variables</title>
 <script type="text/javascript">
 
 var myVariable = 50;
 
 // Variable names (identifiers) have to begin with lower or uppercase letters or an underscore
 // Variable names cannot begin with a number, however they can contain a number
 // To declare a variable, use the keyword var
 // You can assign a value to a variable when you declare it, in one line (as above)
 // ...or you can declare a variable and then assign a value later, as below...
 
 var myVariable2;
 myVariable2 = "Hello there";
 
 document.write(myVariable);
 // This displays the value of myVariable in the browser window
 
 </script>
 
</head>
<body>
 
 
</body>
</html>

This source code shows how create and use variables of different data types. Strings are text (letters, numbers and characters), integers are regular whole numbers (treated as numbers), and floats are real numbers (with decimal places eg. 4.5). Boolean is another data type which is used for true/false values. You’ll also see how to use the HTML br tag to add a new line between text that is displayed in the browser.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Data Types</title>
 <script type="text/javascript">
 //integer
 var age = 20;
 document.write(age);
 
 //float
 var price = 12.95;
 document.write(price);
 
 //string
 var name = "Smith";
 var sentence = "He said \"hello\".";
 
 /*
 Just like in Python, a backslash can be used as an escape character so that
 quotation marks can be used inside a string without any errors
 You can also use single quotes to enclose a string if you want to use double quotes inside a sting
 eg. var sentence = 'He said "hello".';
 */
 
 document.write("</br>", sentence);
 //You can concatenate (join) strings using a comma and you can also use HTML tags inside quotation marks eg. </br>
 //The </br> tag is used to add a new line when the string is displayed in the browser.
 
 </script>
 
</head>
<body>
 
 
</body>
</html>

Hint: Have a look at the toFixed() method if you wish to display floats with a specified number of decimal places.

Next tutorial: Operators

Numbers and Math in Python

This tutorial explains how to use numbers and math functions in Python. To do math in Python, you can use a range of arithmetic operators including:

  • + for addition
  • – for subtraction
  • * for multiplication
  • / for division
  • % for modulus
  • **2 for squared, **3 for cubed, and so on

For example 5*5 will return the value 25. As you can see, it is just like writing any math expression.

View the video below or click here to view it on YouTube.