This problem can be solved elegantly in Flutter.

First, use RegEx in InputFormatter
to make sure users can only enter digits (0-9) and decimal points (.) but not any other characters
inputFormatters: [
// Make sure user can only enter numbers and decimal points
FilteringTextInputFormatter.allow(RegExp(r'[0-9\.]')),
],
Secondly, limit the total input length to 6, so users cannot enter more than that:
maxLength: 6
(Once this is done, Flutter automatically adds a counter, if you don't want the counter, it can be disabled easily by setting counterText: ''
.)
Lastly, monitor the input with a TextEditingController
, and check if the value entered is valid and within range:
bool isValid(String input) {
if (input.isEmpty) return true; // initial empty string is okay
final number = double.tryParse(input); // try to parse the string
if (number == null) return false; // parse failed: invalid format
if (number >= 100) return false; // range failed: larger than 99.999
return true;
}
Full source code:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("TextField Demo")),
body: Center(
child: SizedBox(
width: 200,
child: VerifiedTextField(),
),
),
);
}
}
class VerifiedTextField extends StatefulWidget {
@override
_VerifiedTextFieldState createState() => _VerifiedTextFieldState();
}
class _VerifiedTextFieldState extends State<VerifiedTextField> {
final _controller = TextEditingController();
bool _valid = true;
@override
void initState() {
_controller.addListener(() {
final valid = isValid(_controller.text);
setState(() => _valid = valid);
});
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(
controller: _controller,
inputFormatters: [
// Make sure user can only enter numbers and decimal points
FilteringTextInputFormatter.allow(RegExp(r'[0-9\.]')),
],
maxLength: 6,
decoration: InputDecoration(
errorText: _valid ? null : "Incorrect Format",
// counterText: '', // apply this code, if you don't want a counter
),
);
}
bool isValid(String input) {
if (input.isEmpty) return true; // initial empty string is okay
final number = double.tryParse(input); // try to parse the string
if (number == null) return false; // parse failed: invalid format
if (number >= 100) return false; // range failed: larger than 99.999
return true;
}
}
And of course, if you prefer to do it the way you had in JS, you can modify the isValid
function accordingly.