FAQ: Introduction to PHP Form Validation - Custom Validations

This community-built FAQ covers the “Custom Validations” 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 Custom Validations

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’m stuck on step 4… no matter how much I test my working code, it just won’t complete!!! I’ve tested valid and invalid card numbers. Any idea?

This exercise appears to be bugged and I can’t move on, the code I have seems to be correct but the steps won’t complete.

Hi! I wrote this functions and work properly in the exercise.

if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
card_type = _POST[“credit”];
card_num = _POST[“card-num”];
donation_amount = _POST[“amount”];

if(strlen($card_num)<100){
if($card_type===“mastercard”){
if(preg_match("/5[1-5][0-9]{14}/",$card_num)===1){
$feedback = $success_message;
}else $feedback = $error_message;

}elseif($card_type==="visa"){      if(preg_match("/4[0-9]{12}([0-9]{3})?([0-9]{3})?/",$card_num)===1){
    $feedback = $success_message;
  }else     $feedback = $error_message;
  
}

}else{
$feedback = $error_message;
}

Regards!

I used your code, but it did not work for me. There is no hint or whatsoever… so im a little stuck…
This is my code:

if ($_SERVER[“REQUEST_METHOD”] == “POST”) {

$card_type = $_POST["credit"];

$card_num = $_POST["card-num"];

$donation_amount = $_POST["amount"];

if(strlen($card_num)<100){

if($card_type === “Mastercard”){

if(preg_match("/5[1-5][0-9]{14}/", $card_num) === 1){

  $feedback = $succes_message;

} else {

  $feedback = $error_message; 

}

} elseif($card_type === “Visa”){

if(preg_match("/4[0-9]{12}([0-9]{3})?([0-9]{3})?/", $card_num) 

=== 1) {

 $feedback = $succes_message; 

} else {

$feedback = $error_message;

}

}

} else {

$feedback = $error_message;

}

}

Few things to watch out for…

You’re checking for “Mastercard” and “Visa”

if($card_type === "Mastercard")
elseif($card_type === "Visa")

but, in the HTML, we’re getting the following values:

<option value="mastercard">Mastercard</option>
<option value="visa">Visa</option>

You also assign $feedback the value of $succes_message, but that is not the correct variable name. Re-read the instructions if in doubt.

You’re almost there! Just be careful as to what is asked of you, and you’ll be just fine.

Keep going

1 Like

Hi there! I was trying to understand the filter_var and preg_match in-built functions…i found it little tricky so i decided to take help of the google ,but still it is away from my reach. a helping hand would be good ? thanks!!!

I am stuck on step 3. Just can’t get past it. Tried many different ways. :frowning:

Here is one of my solutions:

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $card_type = $_POST["credit"];
    $card_num = $_POST["card-num"];
    $donation_amount = $_POST["amount"];
// Write your code here:
    $length = strlen($card_num);
    if ($length < 100) {
      if ($card_type === "mastercard") {
          testRegEx("/5[1-5][0-9]{14}/");
      } elseif ($card_type === "visa") {
          testRegEx("/4[0-9]{12}([0-9]{3})?([0-9]{3})?/");
      }
    } else {
      $feedback = $error_message;
    }  
}
function testRegEx ($regex) {
  if (preg_match($card_num, $regex) === 1) {
    $feedback = $succes_message;
  } else {
    $feedback = $error_message;
  }
}

For the above code I get this error:

PHP Fatal error: Cannot redeclare testRegEx() (previously declared in /home/ccuser/workspace/php-form-val-8/src/index.php:29) in /home/ccuser/workspace/php-form-val-8/src/index.php on line 35

Here is another solution, more in line with the instructions:

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $card_type = $_POST["credit"];
    $card_num = $_POST["card-num"];
    $donation_amount = $_POST["amount"];
// Write your code here:
    $length = strlen($card_num);
    if ($length < 100) {
      if ($card_type === "mastercard") {
        if (preg_match($card_num, "/5[1-5][0-9]{14}/") === 1) {
          $feedback = $succes_message;
        } else {
          $feedback = $error_message;
        }
      } elseif ($card_type === "visa") {
        if (preg_match($card_num, "/4[0-9]{12}([0-9]{3})?([0-9]{3})?/") === 1) {
          $feedback = $succes_message;
        } else {
          $feedback = $error_message;
        }
      }
    } else {
      $feedback = $error_message;
    }  
}

For this code I get the error below:

It looks like your code has a syntax error. Check that you’re not missing any semi-colons etc.

Also tried a switch but I’ll leave that out here.
I really can’t see the problem. Anyone? Thanks!

This is closer to what we’re trying to accomplish here. Almost there.


$length = strlen($card_num);
if ($length < 100) {

Could be done in just one line.


if (preg_match($card_num, "/5[1-5][0-9]{14}/")

For the regular expression match, the pattern comes first, subject second.


$feedback = $succes_message;

Instructions state:

If so, assign $feedback the value of $success_message .


These should get you closer to completion. Keep going!

Just an alternative here

> if (strlen($card_num)<100 and $card_type == "mastercard"){ 
>        if(preg_match("/5[1-5][0-9]{14}/",$card_num)){
>        $feedback = $success_message;
>       }else{$feedback = $error_message;}
> }elseif(strlen($card_num)<100 && $card_type == "visa"){
>        if(preg_match("/4[0-9]{12}([0-9]{3})?([0-9]{3})?/",$card_num)){
>        $feedback = $success_message;
>       }else{ $feedback = $error_message;}
>   }else{$feedback = $error_message;}
1 Like

This took me a long time to figure out. But here is my working code:

// Write your code here:

if (strlen($card_num) < 100) {
if ($card_type === “mastercard”) {
if (preg_match("/5[1-5][0-9]{14}/", $card_num)) {
$feedback = $success_message;
} else {
$feedback = $error_message;
}
}

else if ($card_type === “visa”) {
if (preg_match("/4[0-9]{12}([0-9]{3})?([0-9]{3})?/", $card_num)) {
$feedback = $success_message;
} else {
$feedback = $error_message;
}
}
}

if (strlen($card_num) > 100) {
$feedback = $error_message;
}

1 Like

Can anyone tell me why the example regex expressions in the “Custom Validations” section of the PHP course start and end with a forward slash character? This character isn’t mentioned that I can see prior to this section but then suddenly all of the shown regex expressions have it there at the start and end. E.g.

$pattern = '/^[(]*([0-9]{3})[- .)]*[0-9]{3}[- .]*[0-9]{4}$/';
1 Like

I’m stuck on step 3. Keeps telling me that “it” thinks I have a syntax error. “it” kinda sucks since the code runs fine and generates no errors. That means that "it most likely doesnt like something I typed. I’m frustrated. I tried a few other peoples solutions with the same results. Any ideas? I included all of it since I could not see anything wrong with any of it.

Thanks for any help

<?php $feedback = ""; $success_message = "Thank you for your donation!"; $error_message = "* There was an error with your card. Please try again."; $card_type = ""; $card_num = ""; $donation_amount = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $card_type = $_POST["credit"]; $card_num = $_POST["card-num"]; $donation_amount = $_POST["amount"]; // Write your code here: if (strlen($card_num) < 100) { if ($card_type === “mastercard”) { if (preg_match("/5[1-5][0-9]{14}/", $card_num)) { $feedback = $success_message; } else { $feedback = $error_message; } } else if ($card_type === “visa”) { if (preg_match("/4[0-9]{12}([0-9]{3})?([0-9]{3})?/", $card_num)) { $feedback = $success_message; } else { $feedback = $error_message; } } } } if (strlen($card_num) > 100) { $feedback = $error_message; }; ?>

Make a donation

<label for="amount">Donation amount?</label>

  <input type="number" name="amount" value="<?= $donation_amount;?>">

  <br><br>

<label for="credit">Credit card type?</label>

  <select name="credit" value="<?= $card_type;?>">

    <option value="mastercard">Mastercard</option>

    <option value="visa">Visa</option>

  </select>

  <br><br>

  <label for="card-num">Card number?</label>

  <input type="number" name="card-num" value="<?= $card_num;?>">

  <br><br>   

  <input type="submit" value="Submit">

<?= $feedback;?>

I solved the exercise but my issue is that the card type is not saved after submitting form. Does it work for you?

In case it helps anyone, I was also having isues with step 3. I tried so many ways and the issue in the end was that I was using preg_match wrong!

I was doing preg_match( string, expression ), instead of preg_match( expression, string )

Looking at some of the codes in here, I think a lot of us were in the same boat!

1 Like

The preg_match pattern for Visa seems a little strange. Can anyone explain the logic?

This is the pattern: “/4[0-9]{12}([0-9]{3})?([0-9]{3})?/”

If we break it down, it first matches the number “4”, then 12 instances of the numbers 0-9, and then, apparently, an optional extra 3 instances of the numbers 0-9 and another optional extra 3 instances of the numbers 0-9.

As I see it, this would allow a Visa number with a length of 13-16 digits, as both last patterns are optional. And also, they appear to be identical, so what’s the idea?

I’ve tried replacing the pattern with a simpler version that just checks for the number 4, then 15 instances of the numbers 0-9. This works well in my testing, and is a lot simpler.

“/4[0-9]{15}/”

There might be a very good reason for checking the suggested way, but to me it doesn’t make sense.

Hello java1478248818!

A few tips, tricks, and things to consider. Are there multiple buttons on your page? If so you could tie a particular button to the processing code.

For illustration, if you have a button to submit the form and you named that button submit_button you could try the following:

if($SERVER[“REQUEST_METHOD”] == “POST” AND isset($_POST[“submit_button”]) {
#code to format, process, and/or store data
}