How to use InputFormatter on Flutter TextField? - dart

What do I need to insert into TextField(inputFormatters:?
I want to disallow \ and / in one TextField and only allow a to Z in another.

Formatters
In the services library you will find the TextInputFormatter abstract class (this means that you have to import package:flutter/services.dart).
It already has implementations, which are FilteringTextInputFormatter (formerly BlacklistingTextInputFormatter and WhitelistingTextInputFormatter) and LengthLimitingTextInputFormatter.
If you want to implement your own formatter, you can do so by extending TextInputFormatter itself and implementing formatEditUpdate in there.
I will show how to apply the premade FilteringTextInputFormatter with given context.
Examples
disallow \ and /
For this we are going to use the FilteringTextInputFormatter.deny constructor:
TextField(
inputFormatters: [
FilteringTextInputFormatter.deny(RegExp(r'[/\\]')),
],
)
For the Pattern, which needs to be supplied to the formatter, I will be using RegExp, i.e. regular expressions. You can find out more about that here, which also links you to the features I will be using in my examples.
Pay attention to the double backslash \\ and the raw string (r'') in this example. This represents only a single backslash in reality. The reason for this is that backslashes are escape keys in RegExp, so we need to use two backslashes if we want to match the \ character. We would even need quadruple backslashes(\\\\) without the raw string (r'…') because Dart also uses backslashes as escape keys. Using a raw string will ensure that Dart does not unescape characters.
If we were to block a, b, F, !, and ., we would also put it in a list […] like this:
FilteringTextInputFormatter.deny(RegExp('[abF!.]'))
This translates to "deny/blacklist all 'a', 'b', 'F', '!' and '.'".
only allow a to Z
This time we use the FilteringTextInputFormatter.allow constructor:
TextField(
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp('[a-zA-Z]')),
],
)
For this, we are specifying two ranges of characters: a-z and A-Z, which will also accept all the characters (here all the letters) in-between those two specified. This will also work for 0-9 and you can append any character to that list, e.g. a-zA-Z0-9!. will also take ! and . into account.
We can combine this
TextField(
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp('[a-zA-Z]')),
FilteringTextInputFormatter.deny(RegExp('[abFeG]')),
],
)
This is only to show that inputFormatters takes a List<InputFormatter> and multiple formatters can be combined. In reality, you can solve this with one allow/whitelist and a regular expression, but this does work as well.
digitsOnly
There are also already included static properties in the FilteringTextInputFormatter class: one of these is FilteringTextInputFormatter.digitsOnly.
It will only accept/allow digits and is equivalent to an .allow(RegExp('[0-9]')) formatter.

Other options:
lowercase letters : a-z
capital letters : A-Z
lowercase vowels accented : á-ú
capital vowels accented : Á-Ú
numbers : 0-9
space : (a space)
Note: the spacings are to explain better
inputFormatters: [
WhitelistingTextInputFormatter(RegExp("[a-z A-Z á-ú Á-Ú 0-9]"))
]

BlacklistingTextInputFormatter and WhitelistingTextInputFormatter is #Deprecated version 1.20.0
Now you can use FilteringTextInputFormatter to do InputFormatter on TextField or TextFormField.
inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'^ ?\d*')),]
inputFormatters: [FilteringTextInputFormatter.deny(' ')]
inputFormatters: [FilteringTextInputFormatter.digitsOnly]
For e.x
TextFormField(
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly
],
),

First of all you have to check you have imported the following package:
import 'package:flutter/services.dart';
then you can use it like following:
TextFormField(
inputFormatters: [
FilteringTextInputFormatter(RegExp("[a-zA-Z]"), allow: true),
]);

import 'package:flutter/services.dart';
Use these parameters in the TextFormField.
maxLength: 5,
keyboardType: TextInputType.number,
inputFormatters: [WhitelistingTextInputFormatter.digitsOnly,],

Related

How to find a word in a single long string?

I want to be able to copy and paste a large string of words from say a text document where there are spaces, returns and not commas between each and every word. Then i want to be able to take out each word individually and put them in a table for example...
input:
please i need help
output:
{1, "please"},
{2, "i"},
{3, "need"},
{4, "help"}
(i will have the table already made with the second column set to like " ")
havent tried anything yet as nothing has come to mind and all i could think of was using gsub to turn spaces into commas and find a solution from there but again i dont think that would work out so well.
Your delimiters are spaces ( ), commas (,) and newlines (\n, sometimes \r\n or \r, the latter very rarely). You now want to find words delimited by these delimiters. A word is a sequence of one or more non-delimiter characters. This trivially translates to a Lua pattern which can be fed into gmatch. Paired with a loop & inserting the matches in a table you get the following:
local words = {}
for word in input:gmatch"[^ ,\r\n]+" do
table.insert(words, word)
end
if you know that your words are gonna be in your locale-specific character set (usually ASCII or extended ASCII), you can use Lua's %w character class for matching sequences of alphanumeric characters:
local words = {}
for word in input:gmatch"%w+" do
table.insert(words, word)
end
Note: The resulting table will be in "list" form:
{
[1] = "first",
[2] = "second",
[3] = "third",
}
(for which {"first", "second", "third"} would be shorthand)
I don't see any good reasons for the table format you have described, but it can be trivially created by inserting tables instead of strings into the list.

How can I make testing-library's getByText() match a string including a non-breaking space ( )?

I'm trying to match a phone number string that includes a non-breaking space:
assert
.dom(
screen.getByText(
[my text with a non-breaking space]
) as HTMLElement
)
.exists();
However, it is returning this error:
Unable to find an element with the text: [my text with a non-breaking space]. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
How can I test this?
The testing library automatically normalizes whitespace, so the non-breaking space gets converted to a regular space by default. See more about the default behavior at:
https://testing-library.com/docs/queries/about/#normalization
To override this behavior and leave it as a non-breaking space (so that it will match your assert), set the collapseWhitespace parameter to false.
This will look something like this:
assert
.dom(
screen.getByText(
[my text with a non-breaking space],
{ collapseWhitespace: false }
) as HTMLElement
)
.exists();

How do I create a pattern to only match a specific set of characters?

I'm looking for a way search in a string for a very specific set of characters: "(),:;<>#[\]
specialChar = str:find("[\"][%(][%)][,][:][;][<][>][#][%[][%]][\\]")
I'm thinking that there will be no pattern to satisfy my need because of the Limitations of Lua patterns.
I have read the Lua Manual pattern matching section pretty thoroughly but still can't seem to figure it out.
Does anyone know a way I can identify if a given string contains any of these characters?
Note, I do not need to know anything about which character or where in the string it is, if that helps.
To check if a string contains ", (, ), ,, :, ;, <, >, #, [, \ or ] you may use
function ContainsSpecialChar(input)
return string.find(input, "[\"(),:;<>#[\\%]]")
end
See the Lua demo

Why do you use %w[] in rails?

Why would you ever use %w[] considering arrays in Rails are type-agnostic?
This is the most efficient way to define array of strings, because you don't have to use quotes and commas.
%w(abc def xyz)
Instead of
['abc', 'def', 'xyz']
Duplicate question of
http://stackoverflow.com/questions/1274675/what-does-warray-mean
http://stackoverflow.com/questions/5475830/what-is-the-w-thing-in-ruby
For more details you can follow https://simpleror.wordpress.com/2009/03/15/q-q-w-w-x-r-s/
These are the types of percent strings in ruby:
%w : Array of Strings
%i : Array of Symbols
%q : String
%r : Regular Expression
%s : Symbol
%x : Backtick (capture subshell result)
Let take some example
you have some set of characters which perform a paragraph like
Thanks for contributing an answer to Stack Overflow!
so when you try with
%w(Thanks for contributing an answer to Stack Overflow!)
Then you will get the output like
=> ["Thanks", "for", "contributing", "an", "answer", "to", "Stack", "Overflow!"]
if you will use some sets or words as a separate element in array so you should use \
lets take an example
%w(Thanks for contributing an answer to Stack\ Overflow!)
output would be
=> ["Thanks", "for", "contributing", "an", "answer", "to", "Stack Overflow!"]
Here ruby interpreter split the paragraph from spaces within the input. If you give \ after end of word so it merge next word with the that word and push as an string type element in array.
If can use like below
%w[2 4 5 6]
if you will use
%w("abc" "def")
then output would be
=> ["\"abc\"", "\"def\""]
%w(abc def xyz) is a shortcut for ["abc", "def","xyz"]. Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them.

Replace balanced brackets with balanced braces in LaTeX

How can I write a (La)TeX command that replaces all [ with { and all ] with }, assuming that every [ has a matching ], and that any braces between the [ and ] are balanced? It needs to be able to deal with nested brackets.
For example, I want to be able to write a command \mynewcommand so that \mynewcommand{{[[{1}{2}][{3}{4}]]}} is the same as \mycommand{{{{{1}{2}}{{3}{4}}}}}.
Probably the easiest way is to use e-TeX and \scantokens
\newcommand*\mycommand[1]{%
\begingroup
\everyeof{\noexpand}%
\endlinechar=-1\relax
\catcode`\[=1\relax
\catcode`\]=2\relax
\edef\temp{\scantokens{#1}}%
\expandafter\endgroup
\expandafter\def\expandafter\temp\expandafter{\temp}%
}
This will define \temp with the material in #1 but with every "[" ... "]" pair turned into a TeX brace group ("{" ... "}"). You can then use \temp to do whatever you want. As I say, this requires e-TeX, which is available in all modern TeX systems.

Resources