nodegui / nodegui

A library for building cross-platform native desktop applications with Node.js and CSS 🚀. React NodeGui : https://react.nodegui.org and Vue NodeGui: https://vue.nodegui.org
http://docs.nodegui.org
MIT License
8.93k stars 295 forks source link

Add ``setValidator`` method to widget instances that receive input #982

Open hankadler opened 1 year ago

hankadler commented 1 year ago

It'd be great if widgets that accept user input like QLineEdit instances implemented a setValidator method that accepted a function that prohibits input for which it evaluates to false.

For an example of how this is done in PyQt see here.

In JavaScript nodegui it could look something like this:

const { isFloat } = require("validator"); // i.e. validator from npm

//...

const widthLineEdit = new QLineEdit();
widthLineEdit.setPlaceholderText("0.0");
widthLineEdit.setValidator(isFloat)

//...

In the meantime I'm open to workaround suggestions (setInputMask, etc.), I've only just started playing around with nodegui, but so far I'm liking it. Please keep it going. Thank you!

hankadler commented 1 year ago

Here's how I'm solving this at the moment:

// utils/filters.ts

export function filterFloat(text: string): string {
  return text
    .replace(/[^\d.-]/g, "")
    .replace(/(?<=\..*)\./g, "")
    .replace(/(?<=-.*)-/g, "");
}

export function filterUnsignedFloat(text: string): string {
  return text
    .replace(/[^\d.]/g, "")
    .replace(/(?<=\..*)\./g, "");
}
// areaCalculator.ts

// ...

import { filterUnsignedFloat } from "../utils/filters";

// ...

const widthLineEdit = new QLineEdit();
widthLineEdit.setPlaceholderText("0.0");
widthLineEdit.addEventListener(
  "textChanged", (text) => widthLineEdit.setText(filterUnsignedFloat(text))
);