0

I have a select option field that is populated from the database and I wanted to validate when the user does not select anything and press the submit button. I am not able to get the validation.This is what I have done so far:

For the select option list:

<form id="dataForm" method="get" action="">
<b>Year</b>
<?php
$sql = 'SELECT Year_Id,Year_Released FROM {extdb_year} WHERE Only_For_Trend = 0 ORDER BY Year_Released DESC';
$res = db_query($sql);

echo "<select id='Year_Released' name='Year_Released'>
  <option value='-1'>-Select-</option>";
$cnt = 0;
$options = array();
foreach ($res as $row)
{
    $cnt++;
    echo "<option value = '{$row->Year_Id}'";
    if ($cnt==1)
        echo "selected = 'selected'";
    echo ">{$row->Year_Released}</option>";

    $options[$row->Year_Id] = $row->Year_Released;
}
echo "</select>";

?>
<p>
     <input class="submit" type="submit" value="Submit"/>
   </p>
</form>

JQuery code for the validation

$(document).ready(function(){

    $("#dataForm").validate({

    rules: {

        Year_Released: {
            required: true
        }

    },
    messages: {

    Year_Released: "You must select a Year."

    }

    });
});

Any suggestions in this regard will be highly appreciated.

2 Answers 2

0

Your validation code is correct however the first option in your select element must set the value to empty.

echo "<select id='Year_Released' name='Year_Released'>
    <option value=''>-Select-</option>";

Working DEMO: http://jsfiddle.net/qhprG/

0

Put <option value="">Choose an option</option> as blank rather than -1

using jquery validation

rules: {
select: "required" }
2
  • 1
    Your first part is correct, I think that @MohanTimilsina had the actual validation options set correctly.
    – Ryley
    Feb 28, 2013 at 16:37
  • -1 for showing rules that would further break his code. "select" is not the name of his field, and his rules are already properly defined.
    – Sparky
    Feb 28, 2013 at 19:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.