Skip to content

Commit

Permalink
feat: fire a validated event on validation (#1042)
Browse files Browse the repository at this point in the history
  • Loading branch information
mukherjeesudebi authored Apr 18, 2023
1 parent 9d724c2 commit f0e4f9c
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/vaadin-combo-box-mixin.html
Original file line number Diff line number Diff line change
Expand Up @@ -1094,12 +1094,17 @@
}

/**
* Returns true if `value` is valid, and sets the `invalid` flag appropriately.
* Validates the field and sets the `invalid` property based on the result.
*
* The method fires a `validated` event with the result of the validation.
*
* @return {boolean} True if the value is valid and sets the `invalid` flag appropriately
*/
validate() {
return !(this.invalid = !this.checkValidity());
const isValid = this.checkValidity();
this.invalid = !isValid;
this.dispatchEvent(new CustomEvent('validated', {detail: {valid: isValid}}));
return isValid;
}

/**
Expand Down Expand Up @@ -1210,5 +1215,13 @@
* To comply with https://developer.mozilla.org/en-US/docs/Web/Events/change
* @event change
*/

/**
* Fired whenever the field is validated.
*
* @event validated
* @param {Object} detail
* @param {boolean} detail.valid the result of the validation.
*/
};
</script>
34 changes: 34 additions & 0 deletions test/validation.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,15 @@
<script src='../../webcomponentsjs/webcomponents-lite.js'></script>
<link rel="import" href="../src/vaadin-combo-box.html">
<link rel="import" href="helpers.html">
<link rel="import" href="../../test-fixture/test-fixture.html">
</head>

<body>
<test-fixture id="combo-box">
<template>
<vaadin-combo-box></vaadin-combo-box>
</template>
</test-fixture>
<script>
describe('initial validation', () => {
let comboBox;
Expand Down Expand Up @@ -48,6 +54,34 @@
expect(validateSpy.called).to.be.false;
});
});
describe('basic', () => {
let comboBox;

beforeEach(() => {
comboBox = fixture('combo-box');
});

it('should fire a validated event on validation success', () => {
const validatedSpy = sinon.spy();
comboBox.addEventListener('validated', validatedSpy);
comboBox.validate();

expect(validatedSpy.calledOnce).to.be.true;
const event = validatedSpy.firstCall.args[0];
expect(event.detail.valid).to.be.true;
});

it('should fire a validated event on validation failure', () => {
const validatedSpy = sinon.spy();
comboBox.addEventListener('validated', validatedSpy);
comboBox.required = true;
comboBox.validate();

expect(validatedSpy.calledOnce).to.be.true;
const event = validatedSpy.firstCall.args[0];
expect(event.detail.valid).to.be.false;
});
});
</script>

</body>
Expand Down

0 comments on commit f0e4f9c

Please sign in to comment.