1

I have to use an input field, ideally an ui:inputNumber, so the user can only enter numbers. But I also need to put a maxlength on this field and this attribute does not work on ui:inputNumber.

The attribute maxlength works with the field ui:inputText but the user can also enter letters etc. So if I use this field I need to put a restriction on the field if the user enter a letter.

Do you know how to make one or the other way to make this field ?

1
  • This is a HTML5 native feature, don't think we need to do some kind of workaround for such basic feature. added an idea.
    – Raul
    Oct 30, 2018 at 11:54

1 Answer 1

4

Well with a little bit of code you can achieve this. You need to use maxlength attribute to restrict the length and following approach for number only validation.

Have an attribute bound to your inputText

<aura:attribute name="inputN" type="String"/>
<ui:inputText value="{!v.inputN}" keypress="{!c.validate}" keyup="{!c.validate}" keydown="{!c.validate}"  updateOn="keypress, keyup, keydown"/>

In your controller, write validate function:

validate  : function(component, event, helper) {
        var inp = component.get('v.inputN');
        if(isNaN(inp))
            component.set('v.inputN', inp.substring(0, inp.length - 1));
    }

It will on press of each key, check if the whole text is number of not, if not will remove the last entered character.

In case of validating maxlength using ui:inputNumber,

<aura:attribute name="inputN" type="Decimal"/>
    <ui:inputNumber value="{!v.inputN}" keyup="{!c.validate}"  updateOn="keyup"/>

Js function:

validate  : function(component, event, helper) {
        var inp = component.get('v.inputN');
        if(inp.length > 2)
        {
            component.set('v.inputN', parseFloat(inp.substring(0, 2)));
        }
    }
6
  • thanks it works well, but is it possible to use the same "trick" with an ui:inputNumber to truncate the number that the user put, for replace the lack of maxlength ?
    – dou
    Sep 8, 2016 at 12:35
  • I try something like that but it does not work : limit : function(component, event, helper) { var max_chars = 2; var input = component.get('v.number'); if(input.length > max_chars) { component.set('v.number', input.substr(0, max_chars)); } }
    – dou
    Sep 8, 2016 at 13:07
  • Umm.. It does work. use input.substring, not input.substr Sep 8, 2016 at 13:11
  • I try to replace with substring but I am still able to put more than 2 characters in the field
    – dou
    Sep 8, 2016 at 13:22
  • 1
    Ya I just did a POC, you need to change the attribute & ui:inputNumber & JS function. I have updated the answer Sep 8, 2016 at 13:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .