How to check same query in if and else or in a different way server side

DB1
Tera Contributor

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!

@Ankur Bawiskar @Dr Atul G- LNG @Iraj Shaikh @Maik Skoddow 

1 REPLY 1

Aniket Chavan
Tera Sage
Tera Sage

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