Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 51 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

* Keeps form's state and validation results
* Supports any kind of validation functions
* Dirty checking
* Dirty checking (tracks value changes from initial state)
* Separates data from view
* Relies on hooks, but can easily be used with class components

Expand Down Expand Up @@ -87,7 +87,7 @@ Hook that keeps on form field's data.

| Type <div style="width: 200px"></div> | Description |
|---- | ----------- |
| _{<br>&nbsp;&nbsp;&nbsp;value: any,<br>&nbsp;&nbsp;&nbsp;error: boolean<br>&nbsp;&nbsp;&nbsp;dirty: boolean,<br>&nbsp;&nbsp;&nbsp;onChange: (any, config?) => void<br>&nbsp;&nbsp;&nbsp;onBlur: (event, config?) => void<br>&nbsp;&nbsp;&nbsp;setValue: (value: any) => void<br>&nbsp;&nbsp;&nbsp;validate: (any, config?) => boolean or Promise&lt;boolean&gt;<br>&nbsp;&nbsp;&nbsp;reset: () => void,<br>&nbsp;&nbsp;&nbsp;props: {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;value: any,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;onChange: (any, config?) => void<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;onBlur: (event, config?) => void<br>&nbsp;&nbsp;&nbsp;}<br>}_ | Object with field's data and callbacks.<br><br><ul><li>`value` - field's current value</li><li>`error` - is error present flag (`true` if value was validated and didn't pass validation, `false` otherwise)</li><li>`onChange` - callback for change event (changes the value and validates it if previous value wasn't correct)</li><li>`onBlur` - callback for blur event (validates the value)</li><li>`setValue` - function for setting the internal value (does not validate the input, enabling support for async data loading)</li><li>`validate` - function for validating field's value</li><li>`reset` - function for resetting field's data</li><li>`dirty` - indicates whether value of field was changed from initial value</li><li>`props` - set of props that can be spread on standard input elements (same as props in root object, just grouped for better DX)</li></ul><br/>`onChange`, `onBlur` and `validate` functions accept config as last parameter - this will override config from `useValidation` if provided. |
| _{<br>&nbsp;&nbsp;&nbsp;value: any,<br>&nbsp;&nbsp;&nbsp;error: boolean<br>&nbsp;&nbsp;&nbsp;dirty: boolean,<br>&nbsp;&nbsp;&nbsp;onChange: (any, config?) => void<br>&nbsp;&nbsp;&nbsp;onBlur: (event, config?) => void<br>&nbsp;&nbsp;&nbsp;setValue: (value: any) => void<br>&nbsp;&nbsp;&nbsp;validate: (any, config?) => boolean or Promise&lt;boolean&gt;<br>&nbsp;&nbsp;&nbsp;reset: () => void,<br>&nbsp;&nbsp;&nbsp;props: {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;value: any,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;onChange: (any, config?) => void<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;onBlur: (event, config?) => void<br>&nbsp;&nbsp;&nbsp;}<br>}_ | Object with field's data and callbacks.<br><br><ul><li>`value` - field's current value</li><li>`error` - is error present flag (`true` if value was validated and didn't pass validation, `false` otherwise)</li><li>`dirty` - indicates whether current value differs from initial value (useful for enabling Save buttons and tracking changes)</li><li>`onChange` - callback for change event (changes the value and validates it if previous value wasn't correct)</li><li>`onBlur` - callback for blur event (validates the value)</li><li>`setValue` - function for setting the internal value (does not validate the input, enabling support for async data loading; also updates the initial value so `dirty` remains `false`)</li><li>`validate` - function for validating field's value</li><li>`reset` - function for resetting field's data</li><li>`props` - set of props that can be spread on standard input elements (same as props in root object, just grouped for better DX)</li></ul><br/>`onChange`, `onBlur` and `validate` functions accept config as last parameter - this will override config from `useValidation` if provided. |

#### Usage example

Expand Down Expand Up @@ -263,6 +263,55 @@ const onCancel = (data) => alert("Form has been reset");
cancelForm(userFormData, onCancel);
```

### `isDirty(fields)`

Util function for checking if any field in a form has been changed from its initial value. This is useful for enabling/disabling Save buttons based on whether the user has made any changes.

#### Params

| Name | Type <div style="width: 200px"></div> | Required | Description |
| ---- | ---- | ---- | ----------- |
| fields | _{<br/>&nbsp;&nbsp;key: { dirty: boolean },<br/>&nbsp;&nbsp;...<br/>}_ | yes | Form field's data (each field must have `dirty` property - other properties are not important) |

#### Returns

| Type <div style="width: 200px"></div> | Description |
|---- | ----------- |
| _boolean_ | `true` if any field has been changed from its initial value, `false` otherwise |

#### Usage example

```jsx
import { ..., isDirty } from '@enterwell/react-form-validation';

/* useValidation example's code... */

const formData = {
name: useValidation('', isNonEmptyString),
email: useValidation('', isValidEmail)
};

// Load data from API
useEffect(() => {
if (item) {
setValues(formData, {
name: item.name,
email: item.email
});
}
}, [item]);

// Check if form has changes
const hasChanges = isDirty(formData);

return (
<div>
{/* Form inputs */}
<button disabled={!hasChanges}>Save</button>
</div>
);
```

___

_Unless otherwise stated, each validation function will have the following #### Params and #### Returns._
Expand Down
264 changes: 264 additions & 0 deletions cypress/components/isDirty.cy.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,264 @@
import React, { useEffect, useState } from 'react';
import { mount } from '@cypress/react18';
import { useValidation, isDirty, setValues, isNonEmptyString } from '../../src';

describe('isDirty functionality', () => {
describe('useValidation isDirty property', () => {
it('should be false initially', () => {
const Component = () => {
const field = useValidation('initial', isNonEmptyString);

return (
<div>
<p data-testid="dirty">{field.dirty.toString()}</p>
</div>
);
};

mount(<Component />);
cy.get('[data-testid="dirty"]').should('have.text', 'false');
});

it('should be true after onChange', () => {
const Component = () => {
const field = useValidation('initial', isNonEmptyString);

return (
<div>
<input data-testid="input" {...field.props} />
<p data-testid="dirty">{field.dirty.toString()}</p>
</div>
);
};

mount(<Component />);
cy.get('[data-testid="dirty"]').should('have.text', 'false');
cy.get('[data-testid="input"]').clear().type('changed');
cy.get('[data-testid="dirty"]').should('have.text', 'true');
});

it('should be false after onChange back to initial value', () => {
const Component = () => {
const field = useValidation('initial', isNonEmptyString);

return (
<div>
<input data-testid="input" {...field.props} />
<p data-testid="dirty">{field.dirty.toString()}</p>
</div>
);
};

mount(<Component />);
cy.get('[data-testid="dirty"]').should('have.text', 'false');
cy.get('[data-testid="input"]').clear().type('changed');
cy.get('[data-testid="dirty"]').should('have.text', 'true');
cy.get('[data-testid="input"]').clear().type('initial');
cy.get('[data-testid="dirty"]').should('have.text', 'false');
});

it('should remain false after setValue', () => {
const Component = () => {
const field = useValidation('', isNonEmptyString);
const [clicked, setClicked] = useState(false);

useEffect(() => {
if (clicked) {
field.setValue('newInitial');
}
}, [clicked]);

return (
<div>
<input data-testid="input" {...field.props} />
<button data-testid="button" onClick={() => setClicked(true)}>Set Value</button>
<p data-testid="dirty">{field.dirty.toString()}</p>
<p data-testid="value">{field.value}</p>
</div>
);
};

mount(<Component />);
cy.get('[data-testid="dirty"]').should('have.text', 'false');
cy.get('[data-testid="button"]').click();
cy.get('[data-testid="value"]').should('have.text', 'newInitial');
cy.get('[data-testid="dirty"]').should('have.text', 'false');
});

it('should be true after setValue then onChange', () => {
const Component = () => {
const field = useValidation('', isNonEmptyString);
const [clicked, setClicked] = useState(false);

useEffect(() => {
if (clicked) {
field.setValue('newInitial');
}
}, [clicked]);

return (
<div>
<input data-testid="input" {...field.props} />
<button data-testid="button" onClick={() => setClicked(true)}>Set Value</button>
<p data-testid="dirty">{field.dirty.toString()}</p>
</div>
);
};

mount(<Component />);
cy.get('[data-testid="button"]').click();
cy.get('[data-testid="dirty"]').should('have.text', 'false');
cy.get('[data-testid="input"]').clear().type('changed');
cy.get('[data-testid="dirty"]').should('have.text', 'true');
});

it('should be false after reset', () => {
const Component = () => {
const field = useValidation('initial', isNonEmptyString);

return (
<div>
<input data-testid="input" {...field.props} />
<button data-testid="reset" onClick={() => field.reset()}>Reset</button>
<p data-testid="dirty">{field.dirty.toString()}</p>
</div>
);
};

mount(<Component />);
cy.get('[data-testid="input"]').clear().type('changed');
cy.get('[data-testid="dirty"]').should('have.text', 'true');
cy.get('[data-testid="reset"]').click();
cy.get('[data-testid="dirty"]').should('have.text', 'false');
});
});

describe('isDirty helper function', () => {
it('should return false when no fields are dirty', () => {
let result = null;

const Component = () => {
const email = useValidation('initial@test.com', isNonEmptyString);
const name = useValidation('Initial Name', isNonEmptyString);

useEffect(() => {
result = isDirty({ email, name });
}, []);

return <div></div>;
};

mount(<Component />);
cy.then(() => {
expect(result).to.be.false;
});
});

it('should return true when at least one field is dirty', () => {
let result = null;

const Component = () => {
const email = useValidation('initial@test.com', isNonEmptyString);
const name = useValidation('Initial Name', isNonEmptyString);
const [changed, setChanged] = useState(false);

useEffect(() => {
if (changed) {
result = isDirty({ email, name });
}
}, [changed]);

return (
<div>
<input data-testid="email" {...email.props} />
<button data-testid="change" onClick={() => {
email.onChange('changed@test.com', { receiveEvent: false });
setChanged(true);
}}>Change</button>
</div>
);
};

mount(<Component />);
cy.get('[data-testid="change"]').click();
cy.then(() => {
expect(result).to.be.true;
});
});

it('should return false after setValues is called', () => {
let result = null;

const Component = () => {
const email = useValidation('', isNonEmptyString);
const name = useValidation('', isNonEmptyString);
const [loaded, setLoaded] = useState(false);

useEffect(() => {
// Simulate loading data from API
setValues({ email, name }, {
email: 'loaded@test.com',
name: 'Loaded Name'
});
setLoaded(true);
}, []);

useEffect(() => {
if (loaded) {
result = isDirty({ email, name });
}
}, [loaded]);

return <div></div>;
};

mount(<Component />);
cy.wait(100).then(() => {
expect(result).to.be.false;
});
});

it('should return true after setValues then user changes a field', () => {
let result = null;

const Component = () => {
const email = useValidation('', isNonEmptyString);
const name = useValidation('', isNonEmptyString);
const [loaded, setLoaded] = useState(false);
const [changed, setChanged] = useState(false);

useEffect(() => {
// Simulate loading data from API
setValues({ email, name }, {
email: 'loaded@test.com',
name: 'Loaded Name'
});
setLoaded(true);
}, []);

useEffect(() => {
if (changed) {
result = isDirty({ email, name });
}
}, [changed]);

return (
<div>
<input data-testid="email" {...email.props} />
<button data-testid="change" onClick={() => {
email.onChange('changed@test.com', { receiveEvent: false });
setChanged(true);
}}>Change</button>
</div>
);
};

mount(<Component />);
cy.wait(100);
cy.get('[data-testid="change"]').click();
cy.then(() => {
expect(result).to.be.true;
});
});
});
});
Loading