tags:

views:

46

answers:

3

Every time I try to submit the form and I have not entered nothing in the year field I get Incorrect year! how can I still submit the form without having to enter a year. In other words leaving the year field blank and not getting a warning?

Here is the PHP code.

if(preg_match('/^\d{4,}$/', $_POST['year'])) {
    $year = mysqli_real_escape_string($mysqli, $_POST['year']);
} else {
    $year = NULL;
}

if($year == NULL) {
    echo '<p class="error">Incorrect year!</p>';
} else {
    //do something
}
A: 
if(preg_match('/^\d{4,}$/', $_POST['year'])) {
    $year = mysqli_real_escape_string($mysqli, $_POST['year']);
} else if(empty($_POST['year'])){
    $year = '';
} else {
    $year = null;
} 

if($year == NULL) {
    echo '<p class="error">Incorrect year!</p>';
} else {
    //do something
}

Perhaps I'm misunderstanding, but this sounds like what you want.

inkedmn
I still get an Incorrect year.
TaG
if $year is set to an empty string then $year == null will evaluate to true. Change $year == null to $year === null
webbiedave
+1  A: 
if(preg_match('/^\d{4,}$/', $_POST['year'])) {
    $year = mysqli_real_escape_string($mysqli, $_POST['year']);
} else {
    $year = false;
}

if ($year === false) {
    echo '<p class="error">Incorrect year!</p>';
} else {
    //do something
}

OR (if you didn't set YEAR somewhere else)

if(preg_match('/^\d{4,}$/', $_POST['year'])) {
    $year = mysqli_real_escape_string($mysqli, $_POST['year']);
}

if (!isset($year)) {
     echo '<p class="error">Incorrect year!</p>';
} else {
    //do something
}
Ivo Sabev
your second example some what works but know it allows for one character to be entered.
TaG
The problem is in your preg_match not the change I made.
Ivo Sabev
How so? explain please.
TaG
I just tested and it looks working fine. Are you setting $year somewhere else?
Ivo Sabev
But it now lets me add letters and it wont check to see if at least four numbers have been entered.
TaG
Ivo Sabev
A: 
jarvo
You've completely misunderstood the concept of validation. You don't fix the problem by removing the code altogether.
mattbasta