JS/jQuery - Validate start time and end time on a HTML document

2.2k views Asked by At

I have a PHP/HTML page which uses some javascript and jQuery features. I have little to no experience of these coding languages.

I use libraries and tools, so i will list those incase they have the option to provide the solution to my question. Using the current libraries i simply have to type 'required' into the end of an input tag e.g. input name="end_time" type="text" id="end_time" required

I use jQuery timepicker, to select a time by choosing an hour and minutes by 15 minute intervals. What I want to do is ensure that the start time, cannot be greater than the end time.

I've done some research into javascript/jquery and so far I have:

function validateTime(){
var time_1 = document.getElementById("start_time").value;
var time_2 = document.getElementById("end_time").value;
 if (time_1 > time_2) {
  alert("It appears you chose a start time which is later than your end time.");
 }
} 

In theory this should work, but this kind of alert is annoying. Not to mention it would probably run before any input is even entered into the end time input. I would be very interested to know if I could use some of the built in validation popups for this as I want to avoid using an alert.

These are the jQuery files I reference:

code.jquery.com/jquery-1.9.1.js

code.jquery.com/ui/1.10.3/jquery-ui.js

Here is an example of how the default validation popups look: http://oi60.tinypic.com/246lxeu.jpg

I'm a complete amateur when it comes to javascript, and I just happened upon this validation and it works great for what I currently use it for, but I don't have any understanding of which file includes the validation and what is possible using it. If its possible i'd love to use the validation included in jQuery for this purpose.

2

There are 2 answers

0
d.abyss On BEST ANSWER

Given up on JS, PHP validation will suffice.

3
rockStar On

You can use the oninvalid event, you just need to specify the pattern, whether its an alpha numeric or a text or a number.

<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Plz enter on Alphabets ')" />

Here's an updated Fiddle