chefcurry7 chefcurry7 - 1 year ago 104
Javascript Question

Validate a number and allow spaces

I'm currently using redux form to validate some of my fields:

const validate = values => {
const errors = {}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);

if (!values.details) {
errors.details = 'Must declare'

if (! { = 'Required'
} else if(!isNumeric( { = 'Must ne a number'

if (!values.fax) {
errors.fax = 'Required'
} else if(!isNumeric(values.fax)) {
errors.fax = 'Must ne a number'

return errors

My problem is that an entry of "9428 5977" gives a validation error due to the space in between. How can I fix my validation to allow this space?

Answer Source

You can use a RegExp to match your input.

function isNumeric(n) {
    return n && /^[0-9 ]+$/g.test(n);

According to your sample code that mentions a phone and fax, I believe that you do not want something like -3.05E-08 to be valid even if this is a valid finite number.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download