forked from MapComplete/MapComplete
41 lines
1.2 KiB
TypeScript
41 lines
1.2 KiB
TypeScript
import { Translation } from "../../i18n/Translation"
|
|
import Translations from "../../i18n/Translations"
|
|
import { Validator } from "../Validator"
|
|
import { ValidatorType } from "../Validators"
|
|
|
|
export default class FloatValidator extends Validator {
|
|
inputmode: "decimal" = "decimal" as const
|
|
|
|
protected static readonly formattingHasComma = ("" + 1.42).indexOf(",") > 0
|
|
|
|
constructor(name?: ValidatorType, explanation?: string) {
|
|
super(name ?? "float", explanation ?? "A decimal number", "decimal")
|
|
}
|
|
|
|
/**
|
|
*
|
|
* new FloatValidator().isValid("0,2") // => true
|
|
*/
|
|
isValid(str: string) {
|
|
console.log("Is valid?", str, FloatValidator.formattingHasComma)
|
|
if (!FloatValidator.formattingHasComma) {
|
|
str = str.replace(",", ".")
|
|
}
|
|
return !isNaN(Number(str)) && !str.endsWith(".") && !str.endsWith(",")
|
|
}
|
|
|
|
reformat(str: string): string {
|
|
if (!FloatValidator.formattingHasComma) {
|
|
str = str.replace(",", ".")
|
|
}
|
|
return "" + Number(str)
|
|
}
|
|
|
|
getFeedback(s: string): Translation {
|
|
if (isNaN(Number(s))) {
|
|
return Translations.t.validation.nat.notANumber
|
|
}
|
|
|
|
return undefined
|
|
}
|
|
}
|