Showing posts with label number-regex. Show all posts
Showing posts with label number-regex. Show all posts

Tuesday, September 28, 2021

Flutter – How to limit keyboard to allow digits only - How to Make TextField Number only in Flutter - Digits Only Input Keyboard in Flutter – Only Numbers on Text Field - How to Create Number Inputfield in Flutter

This post is just my quick note on how to limit the soft keyboard to allow only digits.

TextField is one of the most commonly used widgets in Flutter. It helps users to enter their text input. In this tutorial, let’s learn how to make the textfield number only by changing the keyboard type in Flutter and apply regex to restrict other than valid numbers.

Kyebord type input only show a keyboard with number inputs, but you can add like 4....4 which is not a number anyway, so let apply regex too to avoid such type of situation.
You can specify the number as keyboard type for the TextField Widget using:
keyboardType: TextInputType.number

Through this option, you can strictly restrict another char without a number.
inputFormatters: [FilteringTextInputFormatter.digitsOnly], keyboardType: TextInputType.number,
Lets apply regex to TextField to avoid unexpected input to TextField:

I'm going to full example, first, created a file named input_validation_utils.dart with following contents:
import 'package:flutter/services.dart';

abstract class StringValidator {
  bool isValid(String value);
}

class DecimalNumberEditValidator extends RegexValidator {
  DecimalNumberEditValidator() : super(regexSource: "^\$|^(0|([1-9][0-9]{0,7}))(\\.[0-9]{0,2})?\$");
}

class RegexValidator implements StringValidator {
  RegexValidator({required this.regexSource});
  final String regexSource;

  /// value: the input string
  /// returns: true if the input string is a full match for regexSource
  bool isValid(String value) {
    try {
      final regex = RegExp(regexSource);
      final matches = regex.allMatches(value);
      for (Match match in matches) {
        if (match.start == 0 && match.end == value.length) {
          return true;
        }
      }
      return false;
    }
    catch (e) {
      // Invalid regex
      assert(false, e.toString());
      return true;
    }
  }
}

class ValidatorInputFormatter implements TextInputFormatter {
  ValidatorInputFormatter({required this.editingValidator});
  final StringValidator editingValidator;

  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    final oldValueValid = editingValidator.isValid(oldValue.text);
    final newValueValid = editingValidator.isValid(newValue.text);
    if (oldValueValid && !newValueValid) {
      return oldValue;
    }
    return newValue;
  }
}
Then we need to apply above validator to a TextField to restrict input other than numbers, now main.dart is looks like:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:p1/input_validation_utils.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final String title = "Regex Input Validation";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: ListView(
        children: <Widget>[
          SizedBox(height: 30,),
          TextField(
            decoration: InputDecoration.collapsed(hintText: '\$0.00'),
            style: TextStyle(fontSize: 32.0, color: Colors.black87),
            textAlign: TextAlign.center,
            keyboardType: TextInputType.number,
            autofocus: true,
            //disabled auto correct if regex failed
            autocorrect: false,
            textInputAction: TextInputAction.done,
            inputFormatters: [
              //applying our custom formatter to TextField
              //so that input other than number can be input
              ValidatorInputFormatter(
                editingValidator: DecimalNumberEditValidator(),
              )
            ],
            onChanged: (value) {
              print("Input=${value}");
            },
          ),
          SizedBox(height: 30,),
          OutlinedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => MyHomePage()),
                );
              },
              child: Text("Forward")
          )
        ],
      ),
    );
  }
}
Sample screen shot as below:

Thursday, November 9, 2017

jQuery Number Text Field Validation Using Regex On Input Field

jQuery Number Text Field Validation Using Regex

Below is the full example of how to validate number using regex


var pattern = new RegExp("(^(\-?)([0-9]{0,12}?)(\\.)([0-9]){0,12}$)|(^(\-?)([0-9]){0,12}$)");

$(document.body).on("keypress", "input[type='text'].number", function (e) {
    if (e.which == 0 || e.which == 8) return true;
    var v = getTextFieldValue(this, String.fromCharCode(e.which));
    $("div").html(v);
    return pattern.test(v);
});

document.addEventListener("paste", function (e) {
    var v, f = $(e.target), ov = f.val();
    if (window.clipboardData && window.clipboardData.getData) { // IE
        v = window.clipboardData.getData('Text');
    }
    else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
        v = e.originalEvent.clipboardData.getData('text/plain');
    }
    else if (e.clipboardData && e.clipboardData.getData) {
        v = e.clipboardData.getData('text/plain');
    }
    v = getTextFieldValue(f[0], v);
    if (!pattern.test(v)) e.preventDefault();
    $("div").html(v);
});

function getTextFieldValue(input, nv) {
    var v = input.value, i = input.selectionStart, j = input.selectionEnd;

    if (i == 0 && j == v.length) return nv;
    else if (i != j || i > 0) return v.substr(0, i) + nv + v.substr(j);
    else if (i == 0) return nv + v;
    else return v + nv;
}

$("input[type='text'].number").focus();


And finally you can use below regex to test your number:
^[-+]?(?:\.[0-9]{1,12}|[0-9]{1,12}(?:\.[0-9]{0,12})?)(?:[eE][-+]?[0-9]{1,12})?$

You can experience above example in JsFiddle

You can also check in regex test environment