Validate a form field with a php and jquery ajax function

advertisements

I'm using wordpress and I have a form that I need to validate. I have an input field to check to make sure it's a valid youtube url. I found this nifty little method using jquery..

  $("input#video_url").change(function (){
    var matches = $(this).val().match(/^(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?(?=.*v=((\w|-){11}))(?:\S+)?$/);
    if (matches) {
      $(".video-validation").append("<span>Valid</span>");
     } else {
      $(".video-validation").append("<span>This is not a valid youtube url</span>");
     }
  });

But then I read that validation like this needs to be done with php, so that it can't be changed on the client-side.

I've been looking for some type of clear tutorial on this but can't find one. So my question is:

How can I turn this validation of the url into a php function in my functions.php and then use that in combination with jquery to do ajax validation before the form can be processed?


Just do a ajax post wit the link:

$.post('validate.php', function(data) {
  $('.result').html(data);
});

And do the same think in your validate.php file something like this:

validate.php

$result = preg_match(/^(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?(?=.*v=((\w|-){11}))(?:\S+)?$/);
if ( $result ) {
  die( '<span>Valid</span>' );
} else {
  die( '<span>This is not a valid youtube url</span>');
}

You end code might look like this:

$("input#video_url").change(function (){
  $.post('validate.php', function(data) {
    $('.video-validation').html(data);
  });
});