From 40e8d8904b006dadab639d4a9fddb926961e658a Mon Sep 17 00:00:00 2001 From: Mehdi Mulani Date: Tue, 18 Oct 2016 08:01:00 -0700 Subject: [PATCH] RN TextInput: don't let user more than maxLength when TextInput already exceeds it Summary: We had a classic integer underflow problem here. Before we would let you type endlessly when the text already exceeded the TextInput maxLength, now we only let you erase characters. There is still a small problem with the TextInput: how do you handle when the value (set from JS) exceeds the maxLength? This could happen pragmatically, just by passing in a very large value or when changing maxLength (e.g. when changing from 4 to 3 digits in the case of a AMEX security code -> VISA security code). Me and achen1 discussed firing onChange in these cases and truncating the number manually (to ensure JS's data model) was aware of the change but it seemed fraught with bugs and general weirdness in what the caller would expect to happen. Reviewed By: javache Differential Revision: D3991210 fbshipit-source-id: dc401c4a7aefe09fa749cd1168d36343d39dc196 --- .../UIExplorer/js/TextInputExample.ios.js | 38 ++++++++++++++++++- Libraries/Text/RCTTextFieldManager.m | 2 +- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/Examples/UIExplorer/js/TextInputExample.ios.js b/Examples/UIExplorer/js/TextInputExample.ios.js index aa548171f..2a8e62f7d 100644 --- a/Examples/UIExplorer/js/TextInputExample.ios.js +++ b/Examples/UIExplorer/js/TextInputExample.ios.js @@ -832,5 +832,41 @@ exports.examples = [ ); } - } + }, + { + title: 'TextInput maxLength', + render: function() { + return ( + + + + + + + + + + + + + + + ); + } + }, ]; diff --git a/Libraries/Text/RCTTextFieldManager.m b/Libraries/Text/RCTTextFieldManager.m index c1d965509..3c125caa3 100644 --- a/Libraries/Text/RCTTextFieldManager.m +++ b/Libraries/Text/RCTTextFieldManager.m @@ -41,7 +41,7 @@ RCT_EXPORT_MODULE() if (textField.maxLength == nil || [string isEqualToString:@"\n"]) { // Make sure forms can be submitted via return return YES; } - NSUInteger allowedLength = textField.maxLength.integerValue - textField.text.length + range.length; + NSUInteger allowedLength = textField.maxLength.integerValue - MIN(textField.maxLength.integerValue, textField.text.length) + range.length; if (string.length > allowedLength) { if (string.length > 1) { // Truncate the input string so the result is exactly maxLength