Skip to content
Snippets Groups Projects
Commit 39127b08 authored by Erwan Rouchet's avatar Erwan Rouchet Committed by Bastien Abadie
Browse files

Properly validate numeric metadata

parent 1a866d7f
No related branches found
No related tags found
1 merge request!1391Properly validate numeric metadata
......@@ -277,12 +277,36 @@ export default {
this.selectedMetadata.name = ''
this.formErrors.name = 'Name may not be empty'
}
if (!this.selectedMetadata.value.trim().length) {
if (!(this.selectedMetadata.value ?? '').toString().trim().length) {
this.selectedMetadata.value = ''
this.formErrors.value = 'Value may not be empty'
}
if (this.selectedMetadata.type === 'date' && !this.validDate) this.formErrors.value = 'This date is invalid'
if (this.selectedMetadata.type === 'url') {
/*
* When a metadata is numeric, we might have an `number` value if it was set by the backend,
* but when it is updated from the v-model, the value will be a string.
*
* To validate that the value is a valid number, we have to go through some JavaScript insanity.
* We need to allow decimal numbers, so parseInt(value, 10) is out of the window.
* parseFloat() may still return a valid float even when we type something like `1 potato`
* because it just stops parsing at the first invalid character. It will therefore parse
* hexadecimal or octal notations as 0, because it will stop at the `x` in `0x4` and just take the 0.
* The unary + operator, suggested by https://stackoverflow.com/a/175787/, will return NaN for `1 potato`
* but will parse `0x4` as 4, which is not supported by the backend. Scientific notation is however acceptable.
* Therefore, to properly validate, we will use the unary + operator and an extra regex to check that it
* looks like it contains only digits, a dot, an E or +- signs.
* This allows `-3`, `+4`, `52`, `52.4`, `.4`, `52.`, `-52.E+4`, `1e8`, etc. which are all valid in Python.
*
* This will need more rewriting once this component switches to TypeScript,
* as a numeric metadata will only allow number values and not string values.
*/
if (this.selectedMetadata.type === 'numeric' && typeof this.selectedMetadata.value !== 'number' && (
!Number.isFinite(+this.selectedMetadata.value) ||
!(/^[0-9.E]+$/i.test(this.selectedMetadata.value))
)) {
this.formErrors.value = 'Value must be a valid number'
} else if (this.selectedMetadata.type === 'date' && !this.validDate) {
this.formErrors.value = 'This date is invalid'
} else if (this.selectedMetadata.type === 'url') {
try {
if (!['http:', 'https:'].includes(new URL(this.selectedMetadata.value).protocol)) this.formErrors.value = 'Only HTTP and HTTPS URLs are allowed'
} catch (err) {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment