Validate if a user exists in the sys_user table using server side validation script

Swarnarghya
Tera Expert

There is a free text field which should contain the user id of sys_user table. now if i try to update that field with some random text it should not allow but if the user id exists it should allow. how to implement this.

1 ACCEPTED SOLUTION

Voona Rohila
Kilo Patron
Kilo Patron

Hi swarnarghya

You can write a before Update BR with trigger as your_field changes with below code

var grSysUser = new GlideRecord('sys_user');
grSysUser.addEncodedQuery("user_name="+current.your_fieldname_here);
grSysUser.query();
if (!grSysUser.next()) {
current.setAbortAction(true);
}

Mark it helpful if this helps you to understand. Accept solution if this give you the answer you're looking for
Kind Regards,
Rohila V
2022-25 ServiceNow Community MVP

View solution in original post

4 REPLIES 4

Voona Rohila
Kilo Patron
Kilo Patron

Hi swarnarghya

You can write a before Update BR with trigger as your_field changes with below code

var grSysUser = new GlideRecord('sys_user');
grSysUser.addEncodedQuery("user_name="+current.your_fieldname_here);
grSysUser.query();
if (!grSysUser.next()) {
current.setAbortAction(true);
}

Mark it helpful if this helps you to understand. Accept solution if this give you the answer you're looking for
Kind Regards,
Rohila V
2022-25 ServiceNow Community MVP

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

Any specific reason to allow free text field/variable?

Why not have reference field/variable to sys_user table?

Users may not know the exact user id to type in free text.

If this is catalog form then you can write onChange client script with GlideAjax to check if that user exists in system.

Regards
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

can we create a separate user table for login and logout activities for an application

Hitoshi Ozawa
Giga Sage
Giga Sage

The question has already been answered but if I wrote the BR, I'll write it as follows.

var grSysUser = new GlideRecord('sys_user');
if (!grSysUser.get("user_name", current.your_fieldname_here)) {
  current.setAbortAction(true);
}

That said, I'll actually just make that field a reference field to sys_user table. This will ensure the field is entered with a valid sys_id of a sys_user table and won't require any BR. It's better to limit the entry to make sure only valid values are entered rather than to let users freely enter and then validate the entry.