jQuery validate select required example 

Joined:
02/21/2009
Posts:
151

February 02, 2012 09:20:22    Last update: February 02, 2012 09:20:22
This example came from the jQuery validation documentation. The required rule can be used to validate a required selection box when you set the value of the first option to empty.
  • Code
  • Demo
<!DOCTYPE HTML> 
<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>

    <script type="text/javascript" 
	    src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js">
    </script>

    <script type="text/javascript">
    jQuery.validator.setDefaults({
	debug: true,
	success: "valid"
    });
    </script>

    <script>
    $(document).ready(function(){
	$("#myform").validate({
	    rules: {
		fruit: "required"
	    }
	});
    });
    </script>

    <style>#fruit { margin-left: .5em; float: left; }
  	#fruit, label { float: left; font-family: Arial, Helvetica, sans-serif; font-size: small; }
	br { clear: both; }
	input, select { border: 1px solid black; margin-bottom: .5em;  }
	select.error { border: 1px solid red; }
	label.error {
	background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/unchecked.gif') no-repeat;
	padding-left: 16px;
	margin-left: .3em;
	}
	label.valid {
	background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif') no-repeat;
	display: block;
	width: 16px;
	height: 16px;
	}
    </style>
</head>
<body>
<form id="myform">
    <select id="fruit" name="fruit" title="Please pick a fruit (from title)!">
	<option value="">Please select a fruit</option>
	<option value="1">Banana</option>
	<option value="2">Apple</option>
	<option value="3">Peach</option>
    </select>
    <br/>
    <input type="submit" value="Validate!" />
</form>
</body>
</html>

The error message is the title since no error message is specified. A more fully defined validation check would look like this:
$('#my-form').validate({
		errorElement: "p",
		errorPlacement: function(error, element) {
                     // place the error with js code
		},
		errorClass:'ui-error', // style the error message
		rules:{
                     // put validation rules here
		},
		messages: {
                     // the message map
                }
});
Share |
| Comment  | Tags