I want to perform custom validation on a form by using Javascript code to capture the onsubmit action of the form. I have tried using the following code (as suggested by http://drupal.org/node/725882) to set the onsubmit attribute of the form to the appropriate Javascript function but it never gets called.

$form['#attributes']['onsubmit'] = ' return func()';

I have inspected my form using

<?php
  print "<pre>";
  print_r($form);
  print "</pre>";
?>

and I noticed the [#attributes] does not have any values in it so I suspect the code to set the onsubmit function is not taking.

Any pointers as to the right course of action would be much appreciated.

Thanks

Comments

WillHall’s picture

What type of validation are you trying to do?

You can do a lot of validation with js...

takinola’s picture

I am trying to check if the user has modified the default text in the input area and prompt the user to enter new data if not

WillHall’s picture

jQuery(function() {
 var defaultvalue = jQuery('#myformfield').val();
 jQuery('#myform').submt(function() {
  var currentvalue = jQuery('#myformfield').val();
  if(currentvalue == defaultvalue) {
   jQuery('#myformfield').addClass('error');
   alert('You need to modify this field');
   return false;
  }
 return;
 });
});
takinola’s picture

Thanks! Where does this go? In the nodetype-edit.tpl.php or in the actual html page header?

WillHall’s picture

You can put it in either. Just need to make sure the ids match up with your form.

takinola’s picture

I still can't get it to work.

I used node-nodetype_edit.tpl.php to set the Id of my form to 'myform' and the id of the text input to 'myforminfield' but nothing happens when the form is submitted.

I am very new to JQuery so there may be some basic step I am missing. Could you please explain in some detail what to do to get this code working?

Thanks

WillHall’s picture

I wasn't suggesting modifying the ids of the fields - use webdev toolbar - or view source and get the existing ids of those items and modify the js snippet.

don't forget to wrap the jQ in script tags

takinola’s picture

Thanks for the help. Your code, with appropriate modifications, worked to solve the problem. In the interest of anyone else reading this exchange, there is a typo in the 3rd line in the original. The code should read

jQuery(function() {
var defaultvalue = $('#myformfield').val();
$('#myform').submit(function() {
  var currentvalue = $('#myformfield').val();
  if(currentvalue == defaultvalue) {
   $('#myformfield').addClass('error');
   alert('You need to modify this field');
   return false;
  }
return;
});
});

I inserted this code in my script.js and was good to go