How to validate dropdownlist in JavaScript

In this article you will see how to put validation in dropdownlist by javascript, suppose first item value of dropdownlist is 0 and text is "-Select-" just like given below and we have to validate that at least one item is selected excluding default i.e "-Select-".

Just copy and paste javascript code given below and pass the parameter dropdownlist id, you can customize alert validation error message according to requirement.

Asp.net server control code :

 <asp:DropDownList runat="server" ID="ddl">
        <asp:ListItem Text="-Select-" Value="0"></asp:ListItem>
        <asp:ListItem Text="One" Value="1"></asp:ListItem>
        <asp:ListItem Text="Two" Value="2"></asp:ListItem>
        <asp:ListItem Text="Three" Value="3"></asp:ListItem>
 </asp:DropDownList>  

Rendered code in html (client side code) :

 <select id="ddl">
        <option value="0">-Select-</option>
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
 </select>

Validate dropdownlist by value field in javascript

      
  function Dropdown_Validation(ddlId) {
        var empty = document.getElementById(ddlId).value;

        if (empty == "0") {
            alert('Please select an item');
            return false;
        }
        return true;
    }
  

Validating dropdown list by text field in javascript

      
    function Dropdown_Validation(ddlId) {
        var ddl = document.getElementById(ddlId);
        var ddlText = ddl.options[ddl.selectedIndex].text;

        if (ddlText == "-Select-") {
            alert('Please select an item');
            return false;
        }
        return true;
    }

  

Validate dropdownlist by selectedIndex property in javascript

      
    function Dropdown_Validation(ddlId) {
        var ddl = document.getElementById(ddlId);
       
        if (ddl.selectedIndex == ) {
            alert('Please select an item');
            return false;
        }
         return true;
    }

  

Recent Article