React - Mobx Validation input Field

2.1k Views Asked by At

I have been searching for a MOBX validation on a input field, but I havent be able to find anything, I found "MobX-input" which requires a form but I dont have any form. another one that I found was "mobx-react-form" with ValidatorJs which again uses form. any hint or example would be appreciated . I just wanna be able to use it on plain input field

 <Input placeholder="FirstName" type="text"
 defaultValue={Contact.FirstName} onChange={(e) => handler(e)} />
1

There are 1 best solutions below

0
On BEST ANSWER

Simple validation is pretty easy to create on your own with MobX. For a single field like this, a simple method for validating the function could look like this:

in the component we have an error field that only shows if the input has been submitted (which could be triggered by a button push or whatever)

return <div>
<input placeholder="FirstName" type="text"
 defaultValue={Contact.FirstName} onChange={(e) => handler(e)} />
{submitted && <span className="error-message">{Contact.FirstNameError}</span>}
</div>;

In the observable class (I used the non-decorator style), we define the field as an observable, and an error message class as a computed value.

class Contact {
  constructor() {
     extendObservable({
       submitted: false,
       FirstName: observable(),
       FirstNameError: computed(() => {
          if(this.FirstName.length < 10) {
             return 'First name must be at least 10 characters long';
          }
          // further validation here
          return undefined;
       })
     })
  }

}

You could easily add an extra hasError computed value that just checks to see if FirstNameError has a value.

This method scales to a few inputs. If you start having a bunch of them, then you'd want to look into an abstraction like a 3rd party library or something you write yourself to manage your validations. You could write a function to generate the computed properties you need based on a little configuration.