material-components / material-components/material-web

Validator do not allow customError

Open
#5,302 2 comments 0 reactions 1 assignee View on GitHub

@christophe-g is already working on this.

Since Dec 15, 2023.

Dominant language
SCSS
Stars
11.3k
Forks
1.1k
Avg merge
20h 28m
Merged PRs (30d)
13

Description

### What is affected?

Accessibility, Component

### Description

A validator using `setCustomValidity` as below will never cause an invalid event to be dispatched.

```ts
export class MyValidator extends Validator{
private checkboxControl?: HTMLInputElement;

protected override computeValidity(state) {
if (!this.checkboxControl) {
this.checkboxControl = document.createElement('input');
this.checkboxControl.type = 'checkbox';
}
this.checkboxControl.setCustomValidity('Get rid of me');

console.warn('I should be invalid', this.checkboxControl.validity)
return {
validity: this.checkboxControl.validity,
validationMessage: this.checkboxControl.validationMessage,
};
}
```

This is due to the [Safari workaround here](https://github.com/material-components/material-web/blob/926edfb367de71eed77deaba45a4a7eaa79342fc/labs/behaviors/constraint-validation.ts#L243), causing the `customError` flag to always be false.

Otherwise new validators are great

### Reproduction

https://lit.dev/playground/#gist=2fecd21c77070203e5472131ffc9b199

### Workaround

Force an error on another flag, but this is not really nice:

```
protected override computeValidity(state: RecordState) {
if (!this.selectControl) {
// Lazily create the platform select
this.selectControl = document.createElement('input');
}
let customError = '';
if(state.currentDuration > state.maxDuration) {
customError = 'Recording is too long';
}
if(customError) {
// we force an error because validator [syncValidation] has a bug
// with customError
this.selectControl.value = '';
this.selectControl.required = true;
this.selectControl.setCustomValidity(customError);
} else {
this.selectControl.value = state.value;
this.selectControl.required = state.required;
}
return {
validity: this.selectControl.validity,
validationMessage: customError || this.selectControl.validationMessage,
// validationMessage: this.selectControl.validationMessage,
};
}
```

### Is this a regression?

No or unsure. This never worked, or I haven't tried before.

### Affected versions

Failing in v1.1.1

### Browser/OS/Node environment

Latest chrome on linux

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.