Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time Validation with Jquery

Tags:

jquery

I am using jquery validation plugin to validate my forms. To validate a text input all I do is write class="required" in the attribute and it does the validation for me.

Now I am trying to validate an input where users will have to enter time( like 02:45:00 AM) but the plugin that I am using doesn't have any function for time validation. So, I have to build a custom validation for that but the problem is I have no knowledge of Jquery :(

Could you please show me how to do this?

Thanks in advance

For your information I need to build it for 12 hr time format

like image 827
black_belt Avatar asked Sep 03 '11 15:09

black_belt


1 Answers

You could use jQuery Validators addMethod().

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery.Validate/1.6/jQuery.Validate.js" type="text/javascript"></script>
<script type="text/javascript">

$().ready(function() {

$.validator.addMethod("time", function(value, element) {  
return this.optional(element) || /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i.test(value);  
}, "Please enter a valid time.");

    $("#login").validate({
            rules: {
                    time: "required time",
            },

     });

 });

 </script>
</head>
<body>
  <form id="login" name="login" method="post" action="#">
  <h1>Time Validation</h1><br />
  <label for="time">Enter Time</label>
  <input id="time" name="time" type="text" value="" tabindex="1" /><br />
  <input id="submit" name="submit" type="submit" value="Submit" tabindex="2" />
</form>
</body>
</html>​

Here is a jsfiddle - http://jsfiddle.net/e2DzT/

I hope this helps.

like image 186
martyhines Avatar answered Oct 13 '22 22:10

martyhines