1
0
mirror of https://github.com/garraflavatra/rolens.git synced 2025-04-19 08:51:03 +00:00

95 lines
2.2 KiB
JavaScript
Raw Normal View History

2023-02-15 19:27:51 +01:00
import { isInt } from '$lib/math';
import { canBeObjectId, int32, int64, uint64 } from '$lib/mongo';
2023-01-29 20:00:15 +01:00
2023-02-15 19:27:51 +01:00
export default function input(node, { autofocus, type, onValid, onInvalid, mandatory } = {
2023-01-29 20:00:15 +01:00
autofocus: false,
type: '',
onValid: () => 0,
onInvalid: () => 0,
mandatory: false,
}) {
const getMessage = () => {
const checkInteger = () => (isInt(node.value) ? false : 'Value must be an integer');
const checkNumberBoundaries = boundaries => {
if (node.value < boundaries[0]) {
return `Input is too low for type ${type}`;
}
else if (node.value > boundaries[1]) {
return `Input is too high for type ${type}`;
2023-01-10 17:28:27 +01:00
}
2023-01-29 20:00:15 +01:00
else {
return true;
2023-01-10 17:28:27 +01:00
}
2023-01-29 20:00:15 +01:00
};
switch (type) {
case 'json':
try {
JSON.parse(node.value);
return false;
}
catch {
return 'Invalid JSON';
}
case 'int': // int32
return checkInteger() || checkNumberBoundaries(int32);
case 'long': // int64
return checkInteger() || checkNumberBoundaries(int64);
case 'uint64':
return checkInteger() || checkNumberBoundaries(uint64);
case 'string':
2023-01-29 20:16:31 +01:00
if (mandatory && (!node.value)) {
2023-01-29 20:00:15 +01:00
return 'This field cannot empty';
}
return false;
2023-01-31 16:58:23 +01:00
case 'objectid':
return !canBeObjectId(node.value) && 'Invalid string representation of an ObjectId';
2023-01-29 20:00:15 +01:00
case 'double':
case 'decimal':
default:
return false;
}
};
const handleInput = () => {
const invalid = getMessage();
if (invalid) {
node.classList.add('invalid');
node.setCustomValidity(invalid);
node.reportValidity();
onInvalid?.();
}
else {
node.classList.remove('invalid');
node.setCustomValidity('');
node.reportValidity();
onValid?.();
2023-01-10 17:28:27 +01:00
}
};
const handleFocus = () => {
node.select();
};
node.addEventListener('focus', handleFocus);
node.addEventListener('input', handleInput);
2023-01-17 17:03:11 +01:00
if (autofocus) {
node.focus();
}
2023-01-10 17:28:27 +01:00
return {
destroy: () => {
node.removeEventListener('focus', handleFocus);
node.removeEventListener('input', handleInput);
},
};
}