How to prevent form submit if an onChange script has generated an error message?

dgmdgmdgm
Kilo Contributor

My scenario is that I have an onChange client script that validates a field, and, if it fails validation, adds one or more error messages to the field. Note that I don't want to do the validation via onSubmit script, as it is more user-friendly to do the validation sooner via onChange script. Also, I don't want to clear an invalid value from the field, as it is more user friendly to let the user correct the field value (guided by the error message(s)) rather than make them start again from scratch.

But my problem is that the user can still submit the form even if the field has failed validation. This seems to me to be a ServiceNow deficiency. Surely the submit form should not be honored if there are one or more field or form error messages being displayed?

So now I am looking for a workaround, that doesn't involve duplicating code, or redoing a validation check that has already been done. Any ideas?

14 REPLIES 14

Community Alums
Not applicable

Hi,

You can check for a specific condition or validation in your 'Onchange' client script and display the error message using:

g_form.showFieldMsg("field_name", "Hello World", "error");

 

The above code will just display error message on change but will not stop the form submission. Let me know in case of any issues.

Cheers,

Hardit Singh

dgmdgmdgm
Kilo Contributor

Thanks, yes, that is exactly the code I am using. 

However, I expected that because I specified "error" (not "information") that form submission would be prevented until the user fixed the error. But this is not the case.  Hence I am now looking for a workaround to prevent form submission. 

Community Alums
Not applicable

The code will show as an error message.

I can of another solution where you can hide/display Submit button and control it in your 'OnChange Client Script'.

 

 

$$('#awc_test')[0].show();

$$('#awc_test')[0].hide();

Cheers,

Hardit Singh

Truong Hoang
Kilo Contributor

Well, I'm thinking about you code something, for example an error message:

current.field_name.setError("Hello World");

and you code sth in an onSubmit event like:

if field_name.getError!=""

return false;

 

Not on SN righr now, cannot know if that work or not. 

Yes, that is basically what I am doing in the onChange script:

g_form.showFieldMsg("field_name", "Hello World", "error");

So an API similar to this:

g_form.getError("field_name");

would be ideal. But there doesn't appear to be anything like this.