How to add a pattern mask to text and limit the amount of characters typed

I need to create a mask for this text field, it is a document, which has 11 digits, and is written as follows: ###.###.###-##.

I also want to limit the quantity and leave only periods and hyphens for typing.

The quantity entered is 11, but with the mask it becomes 14, I don't know if it is possible to block this.

Can anyone help me with this?

{
	"operation": "insert",
	"name": "Input_CPF",
	"values": {
		"type": "crt.Input",
		"multiline": false,
		"label": "$Resources.Strings.PDS_SCCPF_luo5kno",
		"labelPosition": "auto",
		"control": "$PDS_SCCPF_luo5kno"
	},
	"parentName": "FlexContainer_6gej1t9",
	"propertyName": "items",
	"index": 1
}
Like 0

Like

2 comments
Best reply

Hello,

 

In order to create the mask for the text field you can add a handler that will apply formatting to the text field value when user are typing.

 

You can use the following code snippet as an example:

 

{
	request: "crt.HandleViewModelAttributeChangeRequest",
	handler: async (request, next) => {
		if(request.attributeName == "PDS_SCCPF_luo5kno"){
			let value = await request.$context.PDS_SCCPF_luo5kno; 
			value = value.replace(/\D/g, ""); // Remove non-digit characters
			if (value.length > 11){
				value = value.slice(0, 11); // Limit to 11 digits
			}
			let formatted = "";
			if (value.length > 0) {
				formatted += value.slice(0, 3);
			}
			if (value.length >= 4) {
				formatted += "." + value.slice(3, 6);
			}
			if (value.length >= 7) {
				formatted += "." + value.slice(6, 9);
			}
			if (value.length >= 10) {
				formatted += "-" + value.slice(9, 11);
			}
			request.$context.PDS_SCCPF_luo5kno = formatted;
 			request.preventAttributeChangeRequest = true;
		}
		return next?.handle(request);
	}
}

Hello,

 

In order to create the mask for the text field you can add a handler that will apply formatting to the text field value when user are typing.

 

You can use the following code snippet as an example:

 

{
	request: "crt.HandleViewModelAttributeChangeRequest",
	handler: async (request, next) => {
		if(request.attributeName == "PDS_SCCPF_luo5kno"){
			let value = await request.$context.PDS_SCCPF_luo5kno; 
			value = value.replace(/\D/g, ""); // Remove non-digit characters
			if (value.length > 11){
				value = value.slice(0, 11); // Limit to 11 digits
			}
			let formatted = "";
			if (value.length > 0) {
				formatted += value.slice(0, 3);
			}
			if (value.length >= 4) {
				formatted += "." + value.slice(3, 6);
			}
			if (value.length >= 7) {
				formatted += "." + value.slice(6, 9);
			}
			if (value.length >= 10) {
				formatted += "-" + value.slice(9, 11);
			}
			request.$context.PDS_SCCPF_luo5kno = formatted;
 			request.preventAttributeChangeRequest = true;
		}
		return next?.handle(request);
	}
}

Thanks so much.
It worked wonderfully.

Show all comments