Jun 12, 2012 6:57 AM
135 Posts

CSJS validation in onchange event: field loses focus

  • Category: Dojo and Client Side JavaScript
  • Platform: Windows
  • Release: 8.5.3
  • Role:
  • Tags: onChange,focus
  • Replies: 2
I need to validate e-mail address in text field and I'm doing it with client side Javascript in onchange event. The problem is that I cannot get the focus stay in the field if validation fails. This is what I have:

alert("Please enter valid e-mail address.");


return false;
This works in onblur event but the problem there is that onblur SSJS will execute also when I return false which I don't want to happen.
Of course I could move the validation to server side and see how that works. Any ideas how to get the focus stay when validating in client side? I have a couple of workarounds in mind:
- Use setTimeout() to move focus back to the field
- Set field value in CSJS which tells SSJS to exit
But do I really have to use these workarounds for a basic thing like this?

- Panu 

Jun 12, 2012 8:24 AM
126 Posts
Re: CSJS validation in onchange event: field loses focus
The below worked fine for me:
<xp:eventHandler event="onchange" submit="false">
var input = dojo.byId('#{id:inputText1}');
if(input.value == "example")
however if this is for a form entry field and you have access to the ExtLib that comes from openNTF.org or passport advantage, I would suggest using the formTable control and a validator. Validators are already inbuilt, you can apply them to a form element and it won't allow form submission until the issue is resolved. The reason the form table is good is because it will display a yellow box on top of the control with a warning message and a list of all the validation fails and place a red X on top of each field that has failed. It adds a lot of functionality. 
<xe:formRow labelPosition="left" label="test">
<xp:inputText id="inputText1">
<xp:validateExpression message="Failed">
if(getComponent('inputText1').getValue() == "example")
return true;
return false;
Jun 12, 2012 2:18 PM
135 Posts
Re: CSJS validation in onchange event: field loses focus
thank you for looking into this! Did you test with Chrome? I tested originally with IE9 and now also with Chrome and Firefox. The result is that it works only with Chrome!
Thanks also for the ext lib example. I may use it if I decide to go to server side validation (then I would need to change all fields on this form that are required or have validation). So far I haven't used ext lib in real development, just experimented a little bit. If I had an opportunity to build an application from scratch I would definitely build it fully based on ext lib controls. Unfortunately my projects are almost always modifications to applications developed by someone else and I'm waiting for a good opportunity to start adding ext lib stuff. So far I'm still very unfamiliar with ext lib which makes me hesitate a bit before adding it to an existing application.
- Panu