AutoFocus plugin
Focus on the first invalid element when submit form
Usage
You have to use this plugin with
SubmitButton plugin which automatically validate the form when pressing the Submit button. The following piece of code is the starting point to use the AutoFocus plugin:
<html>
<head>
<link rel="stylesheet" href="/vendors/@form-validation/umd/styles/index.min.css" />
</head>
<body>
<form id="demoForm" method="POST">...</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.35.3/es6-shim.min.js"></script>
<script src="/vendors/@form-validation/umd/bundle/popular.min.js"></script>
<script src="/vendors/@form-validation/umd/plugin-auto-focus/index.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function(e) {
FormValidation.formValidation(
document.getElementById('demoForm'),
{
fields: {
...
},
plugins: {
autoFocus: new FormValidation.plugins.AutoFocus(),
submitButton: new FormValidation.plugins.SubmitButton(),
...
},
}
);
});
</script>
</body>
</html>
The sample code above assumes that the FormValidation files are placed inside the vendors
directory. You might need to change the path depending on where you place them on the server.
Options
Option | Type | Description |
---|
onPrefocus | Function | Invoked before the first invalid element get focused |
The onPrefocus
function accepts one parameter:
onPrefocus: function(e) {
}
Using the npm packages
If you are using a bundler such as
Webpack,
Rollup,
Parcel or
Vite, etc., to bundle
your application, then it's recommended to use the FormValidation NPM packages.
$ npm install @form-validation/bundle
$ npm install @form-validation/plugin-auto-focus
- Import and use the AutoFocus plugin:
import { formValidation } from '@form-validation/bundle/popular';
import { AutoFocus } from '@form-validation/plugin-auto-focus';
formValidation(
document.getElementById('demoForm'),
{
fields: {
...
},
plugins: {
autoFocus: new AutoFocus({
...
}),
...
},
}
);
Basic example
Try to press the Add product button to see the first invalid field will be focused. Then fill in the Product name, press the Add product button again. The plugin will bring focus to the Description field which now becomes the first invalid field.
Changelog
- The
onPrefocus
option allows to access the file name via the field
property
- Fixed an issue that the AutoFocus plugin doesn't work. From v1.5.0, it becomes an external plugin
- Added
onPrefocus
option that is useful when you want to activate the tab containing the first invalid field