0

I used jquery to validate a text box placed within update Panel

$("[id*='btnCreate']").live('click', function () 
{
  var regex = new RegExp("^[a-zA-Z0-9]+$");
  if (!regex.test($("[id*='txtbxTemplateName']").val())) 
  {
     alert('hit');

     $("[id*='lblError']").text() = 'Template name is invalid!';

     return false;
  }
});

the click event function is being called, but after returning false it is still hitting the code behind.

Please help me on this.

smv
  • 477
  • 3
  • 11
  • 24

1 Answers1

2

I presume you mean by "still hitting the code behind" that the default action of the button is not being prevented. This is because the code never gets to return false because of an error:

$("[id*='lblError']").text() = 'Template name is invalid!';
return false;

should be

$("[id*='lblError']").text('Template name is invalid!');
return false;

You have just exposed, however, why return false is a bad way to prevent the default action of an event. It is bad because any errors in the error handler will mean that the default action is not prevented, because return false is the last statement in the handler.

If you use event.preventDefault(), all kinds of beautiful things will happen. Chief among them is that you can place the statement earlier in the handler:

$("[id*='btnCreate']").live('click', function (event) {
  var regex = new RegExp("^[a-zA-Z0-9]+$");
  if (!regex.test($("[id*='txtbxTemplateName']").val())) {
    event.preventDefault();
    alert('hit');
    $("[id*='lblError']").text('Template name is invalid!');
  }
});
lonesomeday
  • 233,373
  • 50
  • 316
  • 318