33 lines
972 B
JavaScript
33 lines
972 B
JavaScript
import { Field } from "./Field.js";
|
|
import { ValidationError } from "../ValidationError.js";
|
|
|
|
export class IntField extends Field {
|
|
constructor(key, min, max) {
|
|
super(key);
|
|
this.min = min;
|
|
this.max = max;
|
|
}
|
|
|
|
validate(value) {
|
|
const number = parseFloat(value);
|
|
|
|
if (isNaN(number)) throw new ValidationError(`Field "${this.key}" must be a number`);
|
|
|
|
if (!Number.isInteger(number)) throw new ValidationError(`Field "${this.key}" must be an integer`);
|
|
|
|
if (number < this.min) throw new ValidationError(`Field "${this.key}" must be ${this.min} or greater`);
|
|
|
|
if (number > this.max) throw new ValidationError(`Field "${this.key}" must not exceed ${this.max}`);
|
|
|
|
return true;
|
|
}
|
|
|
|
getInputHtml() {
|
|
return `<input id="${this.id}" type="number" name="${this.key}" min="${this.min}" max="${this.max}" ${this.isRequired ? "required" : ""} placeholder="${this.defaultValue ?? ""}">`;
|
|
}
|
|
|
|
getInputValue() {
|
|
return document.getElementById(this.id).value;
|
|
}
|
|
}
|