FAQ: Introduction to PHP Form Validation - Simple Validation

This community-built FAQ covers the “Simple Validation” exercise from the lesson “Introduction to PHP Form Validation”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn PHP

FAQs on the exercise Simple Validation

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in Language Help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to Language Help and Tips and Resources. If you are wanting feedback or inspiration for a project, check out Projects.

Looking for motivation to keep learning? Join our wider discussions in Community

Learn more about how to use this guide.

Found a bug? Report it online, or post in Bug Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

I have to admit, I was totally thrown by this aspect of question 1: “and the first letter in the input is NOT the correct letter”.

Should it have been obvious that accessing a particular character within a string is done using something like $string[0]? I know previous lessons have demonstrated that you can access values within arrays using indexes, but I can’t recall one that showed that it’s possible with a non-array variable.

I totally understand it now, but not sure if this should have been something I picked up on immediately.

2 Likes

The code in this exercise (and all subsequent) does not seem to work in the real world.
This is specifically what I’m having trouble with
<input type=“text” id=“c-word” name=“c-word” value=<?=$_POST["c-word"]?>>
I get an undefined index error when I try and use a value=<?=$_POST["input-name"]?>
I copied the code from this exercise into my environment and tried to run it and it does not work like it does here in the Codecademy environment.
So how is this supposed to work in a real environment?

1 Like

Hey there, @miq_noatum_it. Welcome to the forums!

This happens when you try to access a variable that has no value assigned to it.

You can either declare your variable, or use the Null coalescing operator (compatible with PHP 7.x). It returns its first operand if it exists and is not NULL ; otherwise it returns the second.

<?= $_POST['c-word'] ?? '' ?>

If you echo gettype($_POST['c-word']);, you’d see that it’s NULL. Therefore the second operand of the Null coalescing operator will be returned which, in this case, is an empty string.

No more error.

2 Likes

Ok so far so good, no error but when I submit an incorrect email (for example) I get my verbiage saying that the email is invalid but it then clears the form. I thought the whole point of doing the value= thing was to keep the fields filled out if the email field failed validation.

Very basic example to illustrate how you can achieve this:

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (! filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    $email_error = 'This is not a valid email address';
    $email = $_POST['email'];
  }
}

?>

<form method="post">
  <input name="email" value="<?= $email ?? '' ?>">
  <span><?= $email_error ?? '' ?></span>
  <input type="submit">
</form>

On error, you’d send back an error message as well as the value provided by the email input field.

2 Likes

Alright, getting better. But what about all the other data in the form fields that aren’t email. Like names, job titles, manager names, check boxes, radio buttons…? Those all get reset. Do I have a script like the above for all form fields?

It’s basically the same idea for most form fields, yeah. Just different validation.

For check boxes and radio buttons, you’ll have to do some digging to figure out how they work.

Thanks for all that. They way you laid out makes more sense though. The $_POST isn’t defined when the form is first loaded.
I’m a little disappointed that they left all of that out of the lesson. Seems like it should be included.

Any suggestion why it doesnt accept my code?

The code works, but still getting an arror at point 2.

   <form method="post" action="">
Enter a word that starts with the letter "a":
<br>
<input type="text" name="a-word" id="a-word" value="<?= $_POST["a-word"]; ?>">
<br>      
  <p class="error" id="a-error"> 
  <?= checkWord($_POST["a-word"],"a");  ?>
  </p>
<br>     
Enter a word that starts with the letter "b":
<br>
<input type="text" id="b-word" name="b-word"
value="<?=$_POST["b-word"]; ?>">
<br>      
     <p class="error" id="b-error"> 
  <?= checkWord($_POST["b-word"],"b"); ?>
  </p>
<br>
Enter a word that starts with the letter "c":
<br>
<input type="text" id="c-word" name="c-word"
value="<?=$_POST["c-word"]; ?>">
<br>      
     <p class="error" id="c-error"> 
  <?=checkWord($_POST["c-word"],"c"); ?>
  </p>
1 Like

Hey,

I don’t see anything particularly wrong, but the exercise checks might expect something specific.

I’d try writing it this way, as one line:

<p class="error" id="a-error"><?= checkWord($_POST["a-word"],"a"); ?></p>

Also, put a space here

<?=checkWord($_POST["c-word"],"c"); ?>
   ^
1 Like

Thank you. That’s why I stopped using Codecademy some month ago. It’s so annoying. They should check results and not formatting. Anyway, its still my favorite site to learn new languages…

1 Like

function checkWord($inp,$abc){
if( ($inp[0]) != $abc){
return "* This word must start with the letter abc!"; } else { return ""; } } So in my above code I was given response that says my code return '* This word must start with the letter z!' I can understand if the correct answer to the exercise requires ( && _SERVER[“REQUEST_METHOD”] === “POST” )
but how is it relevant to the output of this function ?

Thank you so much for posting this!!! I totally get Question 1 now and it was not obvious to me either. Thanks again!

Something that has annoyed me to no end is that they teach you about the ternary operator, which is beautifully simple and efficient, and then they NEVER LET YOU USE IT AGAIN. Would it be possible to change the grader so that it would allow the ternary operator?

1 Like

Hello, I’ve noticed that despite entering the words that starts with a, b and c letters, an error always occur “* This word must start with the letter a/b/c!”. I’ve passed the exercise, but no matter if word begins with correct or incorrect letter, error is always displayed. Has anoyone the same problem? I’m curious if the problem is in my code or the platform?

<?php // Define checkWord() here: function checkWord($input, $letter){ if ($_SERVER["REQUEST_METHOD"] === "POST" && strtolower($input[0]) !== $letter) { return "* This word must start with the letter ${letter}!"; } else { return ""; } } ?> <h1>Time to Practice our ABCs</h1> <form method="post" action=""> Enter a word that starts with the letter "a": <br> <input type="text" name="a-word" id="a-word" value="<?=$_POST["a-word"] ?? '' ?>"> <br> <p id="a-error"><?= checkWord($_POST["name"], "a")?></p> <br> Enter a word that starts with the letter "b": <br> <input type="text" id="b-word" name="b-word" value="<?=$_POST["b-word"] ?? '' ?>"> <br> <p id="b-error"><?= checkWord($_POST["name"], "b")?></p> <br> Enter a word that starts with the letter "c": <br> <input type="text" id="c-word" name="c-word" value="<?=$_POST["c-word"] ?? '' ?>"> <br> <p id="c-error"><?= checkWord($_POST["name"], "c")?></p> <br> <input type="submit" value="Submit Words"> </form> <div> <h3>"a" is for: <?= $_POST["a-word"];?><h3> <h3>"b" is for: <?= $_POST["b-word"];?><h3> <h3>"c" is for: <?= $_POST["c-word"];?><h3> <div>

In the

with the id’s (a-error, b-error, c-error) it looks like it is missing the class error. Just noticed this on your code. Not sure if that would help. Have a safe day! :slight_smile:

1 Like

I get a 404 error on the browser even when I replace my code with the suggested solution… I am not sure if anyone else has the same problem…

I was trying the same thing. It appears that the exercise doesn’t like the extra white space in the <p> tags.

Hello, I fixed like this, might not be the most efficient solution, but I do not get error messages anymore, any advice is welcome

<?php
function checkWord($input, $letter){
   if ($_SERVER["REQUEST_METHOD"] === "POST" && strtolower($input[0]) !== $letter) {
    return "* This word must start with the letter ${letter}!";
   } else {
     return "";
   }
}

if(isset($_POST["a-word"])){
    $word_a = $_POST["a-word"];
}else{
    $word_a = "";
}

if(isset($_POST["b-word"])){
    $word_b = $_POST["b-word"];
}else{
    $word_b = "";
}

if(isset($_POST["c-word"])){
    $word_c = $_POST["c-word"];
}else{
    $word_c = "";
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<h1>Time to Practice our ABCs</h1>
<form method="post" action="">
    Enter a word that starts with the letter "a":
    <br>
    <input type="text" name="a-word" id="a-word" value=<?= $_POST["a-word"] ?? "";?>>
    <br>
    <p class="error" id="a-error"><?= $word_a <> "" ? checkWord($_POST["a-word"], "a") : ""; ?></p>
    <br>
      
    Enter a word that starts with the letter "b":
    <br>
    <input type="text" id="b-word" name="b-word" value=<?= $_POST["b-word"] ?? "";?>>
    <br>
    
    

    <p class="error" id="b-error"><?= $word_b <> "" ? checkWord($_POST["b-word"], "b") : "";?></p>

    <br>
    Enter a word that starts with the letter "c":
    <br>
    <input type="text" id="c-word" name="c-word" value=<?= $_POST["c-word"] ?? "";?>>
    <br>
    <p class="error" id="c-error"><?= $word_c <> "" ? checkWord($_POST["c-word"], "c") : "";?></p>
    <br>
    <input type="submit" value="Submit Words">
</form>
<div>
    <h3>"a" is for: <?= $word_a ?? "";?><h3>
    <h3>"b" is for: <?= $word_b ?? "";?><h3>
    <h3>"c" is for: <?= $word_c ?? "";?><h3>    
<div>  
</body>
</html>