Adding Client-Side Date Validation - PHP and Jquery

For most users, JavaScript will be enabled. It’s far more convenient as a user to get instant feedback on the form, so you will add new jQuery functionality to validate date strings on the client side.

Creating a New JavaScript File to Validate the Date String

Because you’re going to continue to work with this script in the next chapter, you should put it in a separate file in the jsfolder called valid-date.js. This file will contain a function that is functionally equivalent to the _validDate() method in the Calendar class.

It will accept a date to validate, check it against the date-matching regex pattern you wrote previously using match(), and then return true if a match is found or false if match() returns null. You build this function by inserting the following code into valid-date.js:

// Checks for a valid date string (YYYY-MM-DD HH:MM:SS)
// Define the regex pattern to validate the format
var pattern = /^(d{4}(-d{2}){2} (d{2})(:d{2}){2})$/;
// Returns true if the date matches, false if it doesn't

Note:The regex pattern is not enclosed in quotes. If you used quotes, the pattern would be stored as a string and interpreted accordingly—this would result in the script looking for an exact character match, rather than interpreting the regex pattern properly.

Including the New File in the Footer

To use the validDate() function, you’ll need to include the new JavaScript file before init.js, so that the function is available to be called. Do this by opening the common folder and inserting the following bold code:

<script type="text/javascript"
<script type="text/javascript">
wisdomjobs.load("jquery", "1");
<script type="text/javascript"
<script type="text/javascript"

Preventing the Form Submission if Validation Fails

Now that validDate() is available in init.js, you need to add date validation before the form can be submitted. Store the start and end dates in variables (start and end, respectively), then check them using validDate() before allowing the form to be submitted.

Next, modify the click handler to the Submit button on the form that edits or creates events, and then trigger an alert with a helpful error message if either date input has an invalid value. You need to prevent the form from being submitted as well, so the user doesn’t have to repopulate the other form fields.

You accomplish this by inserting the following bold code into init.js:

// Makes sure the document is ready before executing scripts
varprocessFile = "assets/inc/",
fx = {...}
$("li a").live("click", function(event){...});
$(".admin-options form,.admin")
.live("click", function(event){...});
// Edits events without reloading
$(".edit-form input[type=submit]").live("click", function(event){
// Prevents the default form action from executing
// Serializes the form data for use with $.ajax()
varformData = $(this).parents("form").serialize(),
// Stores the value of the submit button
submitVal = $(this).val(),
// Determines if the event should be removed
remove = false,
// Saves the start date input string
start = $(this).siblings("[name=event_start]").val(),
// Saves the end date input string
end = $(this).siblings("[name=event_end]").val();
// If this is the deletion form, appends an action
if ( $(this).attr("name")=="confirm_delete" )
// Adds necessary info to the query string
formData += "&action=confirm_delete"
+ "&confirm_delete="+submitVal;
// If the event is really being deleted, sets
// a flag to remove it from the markup
if ( submitVal=="Yes, Delete It" )
remove = true;
// If creating/editing an event, checks for valid dates
if ( $(this).siblings("[name=action]").val()=="event_edit" )
if ( !validDate(start) || !validDate(end) )
alert("Valid dates only! (YYYY-MM-DD HH:MM:SS)");
return false;
// Sends the data to the processing file
type: "POST",
url: processFile,
data: formData,
success: function(data) {
// If this is a deleted event, removes
// it from the markup
if ( remove===true )
// Fades out the modal window
// If this is a new event, adds it to
// the calendar
if ( $("[name=event_id]").val().length==0
&& remove===false )
fx.addevent(data, formData);
error: function(msg) {
$(".edit-form a:contains(cancel)")
.live("click", function(event){...});

Now save these changes, load http://localhost/ in your browser, and then create a new event with bad parameters using the modal window form

An entry that will fail to validate

An entry that will fail to validate

If you click the Submit button at this point, the validation will fail, and the app will show an alert box with the error message about the date format

The error message in an alert box after failing validation

The error message in an alert box after failing validation

After clicking the OK button in the alert box, the user will be able to edit her entry without having to repopulate any fields.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

PHP and Jquery Topics