Skip to content

Instantly share code, notes, and snippets.

@Kyly
Created November 8, 2018 19:50
Show Gist options
  • Save Kyly/ecaa9f0e5ce0bc6e314b1e474c6c44db to your computer and use it in GitHub Desktop.
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;
}
@Kyly
Copy link
Author

Kyly commented Nov 8, 2018

  1. Why do you need ^ (start) and $ (end)?
  2. Why do you have \\d instead of \d?
  3. Why are you using parens?
  4. Why is i needed?
  5. What are possible inputs to this function?
  6. Per the specification of the RegExp.prototype.test what are valid inputs into the test function?
  7. Is there a way you could format this function without using the function keyword?
  8. Is there a way you could format this function without using a local variable?
  9. Give five inputs and the expected results for each.
  10. Write /^[0-9]*$/ in sentence form. (i.e. /foobar/i A string with the case insensitive character sequence 'foobar')

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