tcomb-form-native
tcomb-form-native copied to clipboard
Changing field type dynamically
I've current got a large form for an personal details and under a condition I would like to change the type of a field which is being enabled.
let BillingDetails = t.struct({
b_email: Email,
b_sign_up: t.Boolean,
b_password: t.maybe(t.String),
.
.
});
If the user select b_sign_up this displays the defaulted hidden b_password, however at this point I want to change the type to t.String and force then user to enter a value.
Currently I'm creating two large structs one with b_password: t.maybe(t.String) and one with b_password: t.String, which is working, however I wondered if there was a way of modifying the fields type through struct or or options e.g. below...
var options = t.update(this.state.options, {
fields: {
b_password: {
hidden: {'$set': !b_sign_up }
'field_type': t.maybe(t.String)
}
}
});
this.setState({options: options, value: value});
Awesome library btw... 👍
Worked it out, by using the extend function I can create an base structure and then merge in type I'm after later.
BillingDetails.extend({
password: t.String
})
I still like the idea though of doing this via the options - if this is possible?
Any more info on this? Suppose a required field named 'X' that is only shown when a field called 'Z' is true.
If Z is true, validation works OK, if I leave X empty I can't continue. But if Z is false, and X remains empty, validation fails but X is hidden.
I think the best approach for tackling this is to expose an option in the struct to automatically skip validation of hidden or disabled fields (with default in false to preserve backwards compatibility). Something like:
var Type = t.struct({
disable: t.Boolean, // if true, name field will be hidden
name: t.String
});
var options = {
skipHiddenFieldsValidation: true, //If true, validation will skip name field ONLY when it's hidden
fields: {
name: {}
}
};