user1084949
user1084949

Reputation: 65

php mandatory field based on drop down list value

I have a form in PHP which has drop downlist and a textboxt which shows and hide bases on dropdown list value. I did the show and hide using javascript.

My question is I want to make the text box mandatory when it become visible and an error to appear if the user left the textbox empty.

I did the form validation using preg_match but how to do the conditional mandatory based on the dropdown list selected value?

EDIT:

here is my show/hide feild in js

<script type="text/javascript">
function showfield(name){
    if(name != 'High School')
        document.getElementById('div1').style.display="block";
    else
        document.getElementById('div1').style.display="none";
}

function hidefield() {
    document.getElementById('div1').style.display='none';
}
</script>

and this is my php validation

if(preg_match("/^[A-Z][a-zA-Z ]+$|\p{Arabic}/u", $_POST["name"]) === 0)
    $errname = '<p class="errText">Please enter your full name </p>';' 

Upvotes: 0

Views: 1653

Answers (2)

Anoop Pete
Anoop Pete

Reputation: 493

Better to come up with a javascript client side scripting.

On submit call javascript function validate()

<form name="xxx" method="get" onsubmit="validate()">

In the javascript function validate(),

<script type="text/javascript">
     function validate(){

     var schoolname=document.getElementById("schoolName");

     var yearofpassing=document.getElementById("yop");

     if(isEmpty(schoolname)){

        alert("schoolname is mandatory");

        document.getElementById("schoolname").value="Please Enter School Name";

        document.getElementById("schoolname").focus();

        return false;
        } // Similarly Give Validation for Year of Passing field

Also if you want specific patterns in the text field, use Javascript match() function Click Here for reference & Usage

     return true;
     }

</script>

Body Part

<body>
<form name="input" action="processinput.php" method="get">
<div id="div1">
   School Name :<input type="text" id="schoolname"> <br>
   Year of Passing : <input type="text" id="yop"><br>
</div>
<div id="div2">
   CODE
<div>
</form>
</body>

Upvotes: 0

Aleks G
Aleks G

Reputation: 57316

What you're missing in your PHP is the check of the dropdown value. In your HTML, you have a text field with name name, which you are checking, but you also have a select element - I don't know the name. In your PHP when checking that the name is empty, first check what value the dropdown is set to. So it would be something like

if($_POST['dropdown'] != 'highschool' &&
   preg_match("/^[A-Z][a-zA-Z ]+$|\p{Arabic}/u", $_POST["name"]) === 0)
{
    $errname = '<p class="errText">Please enter your full name </p>';
}

Upvotes: 1

Related Questions