Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cast number to string? #7

Open
braco opened this issue Jul 1, 2015 · 3 comments
Open

cast number to string? #7

braco opened this issue Jul 1, 2015 · 3 comments

Comments

@braco
Copy link

braco commented Jul 1, 2015

Currently, {cast:true} will convert a string to a number. Is there any reason not to do the opposite?

year: 1972

would become

year: "1972"

but this currently produces "must be of string type"

@4kochi
Copy link
Collaborator

4kochi commented Jul 2, 2015

Well, it's more common to cast a string to a number. You often get strings as an input and it's reasonable to try to convert that string into a number if you are expecting a number. But the other way round is more tricky. Not technical. But more contextual. For example if you have a zipcode or phone number. I guess it would be surprising it it's automatically converted. Maybe i would store it as number and my schema is wrong. And you also have to decide which types should be converted. Because anything could be casted to a string.

But you can actually use the convert function.

var data = {
        zipcode: 12345
    },
    schema = {
        properties: {
            zipcode: {
                type: 'string',
                format: 'integer'
            }
        }
    },
    convertFn = function (format, value) {
        if (format === 'integer') {
            return value.toString();
        }

        return value;
    },
    res = validate(data, schema, {convert: convertFn});

// birthdate was converted
console.log(typeof data.zipcode === 'string'); // true

@TedSoper
Copy link

TedSoper commented Feb 2, 2016

Snippet doesn't work. In my data set using the same format as you the only items that get sent through the convertFn are valid values.

ie: {zipcode: 12345 } never hits convertFn but {zipcode: "12345"} does.

Seems to be the opposite of what we would need.

@4kochi
Copy link
Collaborator

4kochi commented Feb 3, 2016

You are right, the snippet doesn't work. Actually the convert function only triggers if the type of the property is string. One would have to change this behavior so that the convert function is triggered regardless of the current type. Feel free to send a pull request if you are interested in that. We had no use case for this yet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants