MDBValidationItem is never invalid when input contains text


Topic: MDBValidationItem is never invalid when input contains text

bmurphy pro premium asked 2 years ago

Expected behavior

When the "invalid" flag is added to MDBValidationItem, child input should be red and error message that I feed into the "feedback" property should be displayed beneath it

Actual behavior

Form item is only considered invalid when the "required" flag is added to the input AND the input is empty, even when MDBValidationItem invalid flag is set to true

Resources (screenshots, code snippets etc.)

This will only show invalid if the input is empty. Without the "required" flag, it will never be invalid:

<MDBValidationItem feedback="Invalid Text" invalid >
<MDBInput
  name='username'
  onChange={this.onChange}
  id='username'
  required
  label='Username'
  size="lg"
/>
</MDBValidationItem> 

We apply this style only when the input is :invalid. If your input is empty and has the required property, the :invalid will be applied. You probably want to create a custom validation and apply :invalid on your own.

Check this article: https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation#validating_forms_using_javascript


bmurphy pro premium answered 2 years ago

Thank you. For anyone keeping track of invalid inputs in their state, you can use the setCustomValidity method to add the :invalid flag.

this.state.inputs.filter(input => input.invalid).forEach(input => document.getElementById(input.id).setCustomValidity('hello'));

Note: The "hello" will not be displayed, rather the "feedback" in your MDBValidationItem will.

To remove the invalid flag, pass an empty string to setCustomValidity:

this.state.inputs.filter(input => !input.invalid).forEach(input => document.getElementById(input.id).setCustomValidity('')));

Wojciech Staniszewski staff commented 2 years ago

Glad you figured it out!


Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Resolved

Specification of the issue
  • User: Pro
  • Premium support: Yes
  • Technology: MDB React
  • MDB Version: MDB5 4.2.0
  • Device: Dell XPS
  • Browser: Any
  • OS: Any
  • Provided sample code: No
  • Provided link: No