Created
November 8, 2018 19:50
-
-
Save Kyly/ecaa9f0e5ce0bc6e314b1e474c6c44db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function validateNumber(value) { | |
let error; | |
if (!/^('^\\d+$')$/i.test(value)) { | |
error = 'Only numbers allowed'; | |
} | |
return error; | |
} |
- To ensure that the regex check spans the whole string.
- 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
- copy paste error
- it's not. i instructs it to do a case sensitive comparison and we don't need that.
- a string (for entries from old system) or a number:
1
'1'
1.5
- parameter must be a
str
const validateNumber = value => { let error; if (!/^[0-9]*$/.test(value)) { error = 'Only numbers allowed'; } return error; };
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
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);
1.1 = false
'1.1' = false
'1a1' = false
1.1 = false
11 = true
/^[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
^
(start) and$
(end)?\\d
instead of\d
?i
needed?RegExp.prototype.test
what are valid inputs into the test function?function
keyword?/foobar/i
A string with the case insensitive character sequence 'foobar')