Skip to content

Instantly share code, notes, and snippets.

@Kyly
Created November 8, 2018 19:50
Show Gist options
  • Select an option

  • Save Kyly/ecaa9f0e5ce0bc6e314b1e474c6c44db to your computer and use it in GitHub Desktop.

Select an option

Save Kyly/ecaa9f0e5ce0bc6e314b1e474c6c44db to your computer and use it in GitHub Desktop.
function validateNumber(value) {
let error;
if (!/^('^\\d+$')$/i.test(value)) {
error = 'Only numbers allowed';
}
return error;
}
Copy link

ghost commented Nov 8, 2018

  1. To ensure that the regex check spans the whole string.
  2. copy paste error. changed it to [0-9] as this is more efficient as it doesn't allow decimal digits of a number of other character sets
  3. copy paste error
  4. it's not. i instructs it to do a case sensitive comparison and we don't need that.
  5. a string (for entries from old system) or a number: 1 '1' 1.5
  6. parameter must be a str
  7. const validateNumber = value => { let error; if (!/^[0-9]*$/.test(value)) { error = 'Only numbers allowed'; } return error; };

@Kyly
Copy link
Author

Kyly commented Nov 8, 2018

If you're unsure of the type of a variable try using typeof to check.

> typeof 1.2
"number"
> typeof 1
"number"
> typeof '1'
"string"
>Number.isInteger(1.2)
false
> Number.isInteger('1')
false
> Number.isInteger(1)
true

@Kyly
Copy link
Author

Kyly commented Nov 8, 2018

const assert = require('assert').strict;

const validateNumber = value => { 
    let error; 
    if (!/^[0-9]*$/.test(value)) { 
        error = 'Only numbers allowed'; 
    } 
    return error; 
};

try {
    assert.ok(validateNumber('1') === undefined);
    assert.ok(validateNumber('1.1') !== undefined);
    assert.ok(validateNumber(1) === undefined);
    assert.ok(validateNumber(1.1) !== undefined);
} catch(error) {
    console.error(error.message);
    process.exit(1);
}

console.log('Ok!');
process.exit(0);

Copy link

ghost commented Nov 8, 2018

1.1 = false
'1.1' = false
'1a1' = false
1.1 = false
11 = true

Copy link

ghost commented Nov 8, 2018

/^[0-9]*$/ checks if input only consists of the numbers 0-9 appearing 0 or more times

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment