chefcurry7 chefcurry7 - 28 days ago 24
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 (!values.phone) {
errors.phone = 'Required'
} else if(!isNumeric(values.phone)) {
errors.phone = '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

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.