Script for setting character limit on multi-line text field

Shawn Horley
Kilo Guru

Greetings folks

I'm needing to set a specific character limit to a multi-line text field of a form variable. I've seen some other articles about this, but most are older and I am concerned that there may be better ways to do this now, and being an utter novice at writing code I have no idea how to actually script it.

The stuff I have tried cobbling together gives me errors galore when I try to build a catalog client script:

find_real_file.png

So as you can see I'm fairly crap when it comes to coding at this time.

Any suggestions will be mightily appreciated.

Cheers

A.

1 ACCEPTED SOLUTION

No, like this...

function onSubmit() {
	var maxLength = 290; // Add desired max length here
	var varName = 'full_description'; // Add variable name here
	var multi = g_form.getValue(varName);
	var len = multi.length;
	if(len > maxLength){
		var str = multi.slice(0, maxLength);
		g_form.setValue(varName, str);
		g_form.showFieldMsg(varName, 'Max length of ' + maxLength.toString() + ' exceeded for this field.', 'error');
                return false;
	}
}

View solution in original post

10 REPLIES 10

Greetings Mark

Interestingly, I had actually started with your site yesterday, but the form didn't seem to like either example as a catalog client script, and not knowing enough about coding I decided to try something more simple. It's not liking that either however, so I am not sure what I am doing wrong...

 

Cheers

A.

Okay, I missed the 'form variable' part of your initial post.  The catalog makes this a bit more difficult and limited because you need to account for the Service Portal (even if you're not rolling it out there currently).  Service Portal isn't going to allow you the necessary hooks to add a 'keyup' event to make this work perfectly, but you can do a decent job of it with an 'onChange client script like this...

function onChange(control, oldValue, newValue, isLoading) {
	if (isLoading || newValue == '') {
		return;
	}
	
	var maxLength = 20; // Add desired max length here
	var varName = 'max_length'; // Add variable name here
	var multi = g_form.getValue(varName);
	var len = multi.length;
	if(len > maxLength){
		var str = multi.slice(0, maxLength);
		g_form.setValue(varName, str);
		g_form.showFieldMsg(varName, 'Max length of ' + maxLength.toString() + ' exceeded for this field.', 'error');
	}
}

Hi Mark, 

So working with your template, if I wanted it to be an onSubmit script instead, and with a character limit of 290 characters would I do it something like this?

find_real_file.png