I'm trying to create a reusable higher solution for instant/client side form validations in react.
I thought of creating a validation class with validation methods and simply passing the relevant ones to the form fields.
So for example if I have a required email field it will be passed two methods from the validation class to check that.
Here's an abbreviated example:
class Validate {
constructor (value) {
this.value = value
}
required = () => {
console.log('in validator required, value is :', this.value)
if (!this.value.toString().trim().length) {
return 'required'
}
}
lt = () => {
if (this.value.toString().trim().length < 50) {
return 'extra details must be at least 50 characters'
}
}
}
export default class Form extends Component {
constructor () {
super()
this.validate = new Validate(this.state.email) // Passing the field to the instance here means it will be undefined even after the state changed with new value for email.
}
/* ... */
render () {
const {
email
} = this.state.value
const {
required
} = this.validate
return (
<form className='form__wrapper' onSubmit={this.onSubmit}>
<InputText
type='text'
value={email}
validations={required}
/* ... */
/>
</form>
)
}
}
const InputText = ({ value, validate }) => (
<div className={`field-wrapper ${customClass}`} >
<input
value={value}
/* ... */
/>
{value ? validate(value) : null}
</div>
)
My problem as, you can see from the comment above, is that I don't know how to pass my variables to the class so they will get updated when the user input data and the value of the email field has changed.
this. Whenvalidateis called, it will not be called with the appropriatethis. Try replacingconst { required } = this.validatewithconst required = this.validate.required.bind(this.validate)