-
Notifications
You must be signed in to change notification settings - Fork 6
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
Comments
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 |
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. |
You are right, the snippet doesn't work. Actually the convert function only triggers if the type of the property is |
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"
The text was updated successfully, but these errors were encountered: