How to check same query in if and else or in a different way server side
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-31-2024 05:43 AM
Hello All,
I have the following server side script to validate a query with if condition and else condition
var email = input.nonUser.Useremail;
if(!email.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/)){
emailValid = 'false';
gs.addErrorMessage('Enter a valid email address');
}
if(emailValid == 'true'){
var gr = new GlideRecord("sys_user");
gr.addQuery("email",input.nonUser.Useremail);
gr.addEncodedQuery("emailNOT LIKEabc");
gr.query();
if (gr.next()) {
gr.update();
}
else
{
gr.initialize();
....
gr.insert();
}
}
The above code checks for a valid email and if yes it queries the table.
The issue is - I enter an email which does not contain "abc" in email which directly goes to the else part and creates a new record which is not expected.
Expected is to have that else part check if email does not contain "abc"/ it should restrict the insertion too because it does not validate the existing email id too. It simply creates an empty user record with same email.
Need help with the same.
Thanks!
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-31-2024 06:39 AM
Hello @DB1 ,
Please give a try to the code below and see how it works for you.
var email = input.nonUser.Useremail;
var emailValid = true; // Assume email is valid initially
if (!email.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/)) {
emailValid = false;
gs.addErrorMessage('Enter a valid email address');
}
if (emailValid) {
var gr = new GlideRecord("sys_user");
gr.addQuery("email", input.nonUser.Useremail);
gr.query();
if (gr.next()) {
// Email exists, perform update or any other logic
gr.update();
} else {
// Email does not exist, perform insert
gr.initialize();
gr.setValue('email', input.nonUser.Useremail); // Set other fields as needed
gr.insert();
}
}
Let me know your views on this and Mark ✅Correct if this solves your query and also mark 👍Helpful if you find my response worthy based on the impact.
Thanks,
Aniket