Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to accept minimum length and maximum length of a string from the user

Pratiksha Lang1
Kilo Sage

How to accept minimum length and maximum length of a string from the user

I have written a OnChange Catalog client script for the same. This script works fine if I want to accept length 10, In this I also want to accept it if length is 4. I want it to accept both length 10 and 4, if it is not 10 or 4 then it should throw an error.

 

 

function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}var letterNumber = /^[0-9a-zA-Z]+$/;


if(!(newValue.match(letterNumber)) || newValue.toString().length>10 || newValue.toString().length<10)
{
alert('It accepts only 10 digits or character');
g_form.setValue('vehicle_registration_no', '');

}

1 ACCEPTED SOLUTION

sanket16
Giga Guru

Hi @Pratiksha Lang1 

Please try below code:

---------------------------------------------

var regexcheck=/^[A-Za-z0-9]*$/.test(newValue);
len=newValue.toString().length;
if(regexcheck &&(len==4 || len==10 )){
//do nothing
}else{
alert("Your error msg");
}

View solution in original post

9 REPLIES 9

I want to do it with the help of regex

what validation do you want to do with Regex, its not mentioned in your question ? are you trying to exempt special char ?


☑️ Please mark responses as HELPFUL or ACCEPT SOLUTION to assist future users in finding the right solution....

LinkedIn - Lets Connect

sanket16
Giga Guru

Hi @Pratiksha Lang1 

Please try below code:

---------------------------------------------

var regexcheck=/^[A-Za-z0-9]*$/.test(newValue);
len=newValue.toString().length;
if(regexcheck &&(len==4 || len==10 )){
//do nothing
}else{
alert("Your error msg");
}

Sai Kumar B
Mega Sage

@Pratiksha Lang1 

Try using regex

 

var regexcheck=/^[A-Za-z0-9]*$/.test(newValue);
var minLengthCheck = /^[a-zA-Z]{4}$/.test(newValue); //Regex to check minimum length
var mxLengthCheck = /^[a-zA-Z]{10}$/.test(newValue); //Regex to check maximum length

if(regexcheck && (minLengthCheck  || mxLengthCheck )){
//do nothing
}else{
alert("error msg");
g_form.clearValue('vehicle_registration_no');
}

 

Arava Gopi
Tera Contributor

Hi Pratiksha,

Please try the below code...

function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
var letterNumber = /^[0-9a-zA-Z]+$/;
if (newValue.match(letterNumber) != null) {
if (newValue.toString().length != '10' && newValue.toString().length != '4') {
g_form.setValue('vehicle_registration_no', '');
alert('It accepts only digits or character with length of 4 or 10');//Change the alert message accordingly
}
}
else{
alert("Please Enter Digits or Characters only, Vehicle Number won't accepts special characters");
}
}

Thanks & Regards,

Gopi