Skip to content

Numeric string validator. #39

@andersonjoseph

Description

@andersonjoseph

I was using the validator and I noticed that I can't validate numeric strings. I was trying with:

const v = new Validator;

const schema = {
  price: {type: 'number', convert: true}
}

const uno = {
  price: '100.30'
}

const dos = {
  price: '10x0.30'
}

const tres = {
  price: 's'
}

const cuatro = {
  price: ''
}

console.log(v.validate(uno, schema)); // true
console.log(v.validate(dos, schema)); // error
console.log(v.validate(tres, schema)); // error
console.log(v.validate(cuatro, schema)); // true :(

So I made a 'numeric String' rule using a regExp /^-?[0-9]\d*(\.\d+)?$/

const schema = {
  price: {type: 'string', numeric: true}
}

const uno = {
  price: '123'
}

const dos = {
  price: '12.30'
}

const tres = {
  price: ''
}

const cuatro = {
  price: '12x'
}

console.log(v.validate(uno, schema)); // true
console.log(v.validate(dos, schema)); // true

console.log(v.validate(tres, schema)); // error {type: stringNumeric, message: 'The field price must be a numeric string,
                                       // expected: A numeric string, actual: ''}

console.log(v.validate(cuatro, schema)); // error {type: stringNumeric, message: 'The field price must be a numeric string', 
                                         // expected: A numeric string, actual: '12x'}

What do you think? If it can merge it I can write tests and make a PR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions