Custom Validation Rules Bronze Plan
Although we offer many validation rules, sometimes you may need to add your own custom rules. If that's your case, then you're in luck! With KwesForms you can add custom validation rules that validate as you type and on blur like our own validation rules.
With our NPM Package
In order to add custom validation rules, call kwesforms.setCustomRule()
method in the mounted method or hook of your component/view. This function takes 4 arguements:
- Your form's id.
- The field's name that needs validation.
- The error message for your custom rule.
- A function containing the rule's logic. Your function must:
- Accept a "value" arguement.
- Return a boolean. "true" would trigger the validation error.
<form ... class="kf-form" id="myForm"> <input type="email" name="email"> <button type="submit">Submit</button> </form>
...
<!-- In your js file --> import kwesforms from 'kwesforms';
...
const errorMessage = 'No Gmail accounts allowed!';
kwesforms.setCustomRule( 'myForm', 'email', errorMessage, value => { return value.indexOf('@gmail.com') > -1; } );
With our CDN
Implementation
In order to add custom validation rules, your form must have a unique id
. Next you must listen for our kwCustomRulesSet
event on your form element and call our global setCustomKwRule
function. This function takes 4 arguements:
- Your form's id.
- The field's name that needs validation.
- The error message for your custom rule.
- A function containing the rule's logic. Your function must:
- Accept a "value" arguement.
- Return a boolean. "true" would trigger the validation error.
Example
Below is an example of a custom validation rule on the "email" field, that doesn't accept Gmail accounts.
<form ... class="kf-form" id="myForm"> <input type="email" name="email"> <button type="submit">Submit</button> </form>
...
<!-- Add this script after your KwesForms script --> <script> var form = document.getElementById('myForm'); var errorMessage = 'No Gmail accounts allowed!';
form.addEventListener('kwCustomRulesSet', function () { window.setCustomKwRule( 'myForm', 'email', errorMessage, function (value) { return value.indexOf('@gmail.com') > -1; } ); }); </script>
Notice anything wrong in our docs? Let us know.