Sowmya
Sowmya

Reputation: 26989

Validation for select box

I am doing a form validation using jquery. I am not getting how to validate the select list menu.

Could you please help me out with this.

Here is my code and FIDDLE

$.validator.setDefaults({
    submitHandler: function() { alert("submitted!"); }
});

$().ready(function() {
    // validate the comment form when it is submitted
    $("#commentForm").validate();

    // validate signup form on keyup and submit
    $("#signupForm").validate({
        rules: {
            firstname: "required",
            lastname: "required",           
            email: {
                required: true,
                email: true
            },
            topic: {
                required: "#newsletter:checked",
                minlength: 2
            },
            agree: "required"
        },
        messages: {
            firstname: "Please enter your firstname",
            lastname: "Please enter your lastname",
            username: {
                required: "Please enter a username",
                minlength: "Your username must consist of at least 2 characters"
            },
            email: "Please enter a valid email address",
            agree: "Please accept our policy"
        }
    });



});

Upvotes: 1

Views: 20177

Answers (3)

anjan
anjan

Reputation: 1

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

</head>
<body>
<center>
<h2>Registration</h2>
<form  method="get" id="register" action="register.php">
    <table  bgcolor="#CC99FF">
             <tr>
                        <td>Name</td>
                        <td>
                       <input type="text" id="name" name="name" value="" />
                        </td>
                    </tr>

                    <tr>
                        <td>Mobile Number</td>
                        <td>
                            <input type="text"  id="mobile" name="mobile" value="" maxlength="10" />
                        </td>
                    </tr>

                    <tr>
                        <td>EmailId</td>
                        <td><input type="text" id="email" name="email" value="" /></td>
                    </tr>
                    <tr>
                        <td>Gender</td>
                        <td><input type="radio" id="gender" name="gender" value="male" />Male<input type="radio" id="gender" name="gender" value="female" />Female</td>
                    </tr>
                    <tr>
                    <tr>
                        <td>Sports</td>
                        <td><input type="checkbox" id="hobby" name="hobby[]" value="cricket" />Cricket<input type="checkbox" id="hobby" name="hobby[]" value="tennis" />Tennis<input type="checkbox" id="hobby" name="hobby[]" value="football" />Football</td>
                    </tr>

                    <tr>
                        <td>Stat</td>
                        <td><select name="state" id="state">
                        <option value="0">Please select any one!</option>
                        <option value="Gujarat">Gujarat</option>
                        <option value="Rajastan">Rajastan</option>
                        <option value="Panjab">Panjab</option>
                        <option value="Madya Pradesh">Madya Pradesh</option>
                        </select></td>
                    </tr>
                    <tr>

                        <td colspan="2" align="center"><input type="submit" name="submit" value="Submit" /></td>
                    </tr>
                   </table>
</form>
</center>
</body>
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script>
    $(document).ready(function(e) {
        $("#register").submit(function(e){

            var error=0;
            var name = $("#name").val();
            var mobile = $("#mobile").val();
            var email = $("#email").val();
            var email_pattern = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$/;
            var character_pattern=/^[a-z]+$/;
            var num_pattern=/^[0-9]+$/;

                if(name==""){
                    alert("Please Enter Name");
                    error=1;
                }
                else if(character_pattern.test(name)){
                    //alert("valid name");
                }else{
                    alert("Only Charecter Allowed In Name Field !");
                    error=1;
                }

                if(mobile==""){
                    alert("Please Enter Mobile");
                    error=1;
                }
                else if(num_pattern.test(mobile)){
                    //alert("valid mobile number");
                }else{
                    alert("Only Number Allowed In Mobile Field !");
                    error=1;
                }


                if(email==""){
                    alert("Please Enter email");
                    error=1;
                }
                else if(email_pattern.test(email)){
                    //alert("valid email");
                }else{
                    alert("Please Enter Valid email");
                    $("[name=email]").css("background-color","red");
                    error=1;
                }

                if($("#gender:checked").length == 0)
                {
                    alert("Please Select Any Gender!");
                    error=1;

                }

                if($("#hobby:checked").length == 0)
                {
                    alert("Please Select hobbys!");
                    error=1;

                }

                if( $("#state").val() == '0' )
                {
                    alert("Please Select State!");
                    error=1;

                }

                 if (error) {
                    return false;
                 } else {
                    return true;
                 }
        });

    });

</script>
</html>

Upvotes: -1

Praveen
Praveen

Reputation: 56539

1) set an ID for select tag.

2) create a default option with empty string as value.

<option value="">select an option</option>

<select id="country" name="country"> <!--SET AN ID-->
        <option value="">select an option</option> <!--DEFAULT OPTION-->
        <option value="Afghanistan">Afghanistan</option>
        <option value="Albania">Albania</option>
        <option value="Algeria">Algeria</option>
        <option value="American Samoa">American Samoa</option>
        <option value="Andorra">Andorra</option>
        <option value="Angola">Angola</option>
        <option value="Anguilla">Anguilla</option>
        <option value="Antarctica">Antarctica</option>
        <option value="Antigua &amp; Barbuda">Antigua &amp; Barbuda</option>
        <option value="Antilles, Netherlands">Antilles, Netherlands</option>
        <option value="Arabia, Saudi">Arabia, Saudi</option>
        <option value="Argentina">Argentina</option>  
</select>

In JS, add the below code in validate method,

within rule block

country: {
    required: true
 }

within messages block

country: "Please select an option"

check this working Fiddle

FYI: mandatory fields should be prefixed or suffixed with * to show difference.

Hope you understand.

Upvotes: 3

Akki619
Akki619

Reputation: 2432

The problem with your code is, you have Afghanistan selected by default. How it will show required error message when value is present.

Have you considered below simple solution, it works like a charm provided you should have empty value selected. Add class="required" to you select tag.

<select name="country" class="required">
<option value="">Afghanistan</option>

Upvotes: 0

Related Questions