logo

NJP

Validate Email ID using Regex

Import · Dec 13, 2021 · article

Validate an Email ID using Regex ?

There are many articles already posted on this by Nishat, Ankur etc. I am trying to recollect the things and put it in a manner so that one can directly use it without any hassle.

1. Using inbuilt Regex option in Service catalog :-

When we add variables to service catalog, we can use default Regex validation option available for Email ID, IP address, Zip code, Number and URL.

image

2. Customized Email ID validation :

If Email ID requirement is like below:

/*

1. max length = 30

2. before @ 4 to 16

3. after @ and before . 3 to 10

4. ending with .com or .co.in

5. first letter small case alphabet

*/

2.1 ]

function onChange(control, oldValue, newValue, isLoading, isTemplate) {

if (isLoading || newValue === '') {

return;

}

var regex = /[a-z][a-zA-Z0-9.-]{3,15}@[a-zA-Z0-9]{3,10}.(com|co.in)/;

newValue = newValue.toString();

var isValidFormat = regex.test(newValue);

if(!isValidFormat){

g_form.addErrorMessage('Please enter valid email address.');

g_form.addErrorMessage('1. max length = 30');

g_form.addErrorMessage('2. before @ 4 to 16');

g_form.addErrorMessage('3. after @ and before . 3 to 10');

g_form.addErrorMessage('4. ending with .com or .co.in');

g_form.addErrorMessage('5. first letter small case alphabet');

g_form.clearValue('u_email_new');

}

}

2.2]

function onChange(control, oldValue, newValue, isLoading, isTemplate) {

if (isLoading || newValue === '') {

return;

}

var email = g_form.getValue('u_email_new');

if(!email.match(/[a-z][a-zA-Z0-9.-]{3,15}@[a-zA-Z0-9] {3,10}.(com|co.in)/)){

g_form.addErrorMessage('Please enter a valid email ID);

g_form.setValue('u_email_new','');

}

}

2.3]

function onSubmit() {

g_form.hideErrorBox('u_email_new');

var email = g_form.getValue('u_email_new');

return validateEmail(email);

}

function validateEmail(email) {

if (!email || email.trim().length <= 0)

return true;

var regex = /[a-z][a-zA-Z0-9.-]{3,15}@[a-zA-Z0-9] {3,10}.(com|co.in)/;

if (!regex.test(email)) {

g_form.showErrorBox('u_email_new', getMessage('Invalid Email ID'));

return false;

}

return true;

}

If this article is useful for you to understand Email validation , please take some time and efforts to mark article as Helpful. Thank you for your time !!!

Warm Regards,

Rishikesh

View original source

https://www.servicenow.com/community/itsm-articles/validate-email-id-using-regex/ta-p/2307653