Giter VIP home page Giter VIP logo

form-validation's Introduction

FormValidation

The best validation library for JavaScript.

FormValidation

Biggest collection of validators

40+ validators, 50+ plugins

  • Cover most various types of form field
  • Develop, reuse custom validator
  • Support sync and async validators
  • Plugin based architectue

Flexible

  • Customize icon
  • Customize error message
  • Customize error message location
  • Customize valid and invalid colors
  • Dynamic field
  • Enable, disable validators on the fly

Localization

  • Language packages for error message
  • Support custom message
  • Support custom validators
  • Switch between locales
  • Validate ID and VAT numbers in many countries

Declaring validation rules

  • Declarative mode
<form id="registrationForm">
    <input
        name="userName"
        data-fv-not-empty="true"
        data-fv-not-empty___message="The username is required"
        data-fv-string-length="true"
        data-fv-string-length___min="6"
        data-fv-string-length___message="The name must be more than 6 characters long"
    />
</form>
  • Programmatic mode
FormValidation.formValidation(
    document.getElementById('registrationForm'),
    {
        fields: {
            userName: {
                validators: {
                    notEmpty: {
                        message: 'The username is required',
                    },
                    stringLength: {
                        message: 'The name must be more than 6 characters long',
                        min: 6,                        
                    },
                },
            },
        },
    },
);

Integration with your stack

  • Support native form
  • Support popular CSS frameworks via plugins
  • Support popular JavaScript frameworks
  • Easy to integrate with a framework

Play nice with form libraries

  • Autocomplete
  • Color picker
  • Custom checkbox
  • Custom radio
  • Date picker
  • International telephone input
  • Mask input
  • Rich editor
  • Select
  • Star rating
  • Tag input
  • Time picker
  • Toggle
  • Wizard

and more!

Supported browsers

Support the latest version of

  • Chrome
  • Firefox
  • Safari
  • Opera
  • Edge
  • Internet Explorer 11

About

This project is developed by Nguyen Huu Phuoc. I love building products and sharing knowledge.

Be my friend on

form-validation's People

Contributors

dependabot[bot] avatar joshm91 avatar phuocng avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

form-validation's Issues

Shorten import paths

https://formvalidation.io/guide/examples/bundling-with-rollup

// Current
import formValidation from 'formvalidation/dist/es6/core/Core';

// Use the plugins
import Icon from 'formvalidation/dist/es6/plugins/Icon';
import Trigger from 'formvalidation/dist/es6/plugins/Trigger';
import Bootstrap from 'formvalidation/dist/es6/plugins/Bootstrap';

By updating the webpack/rollup alias, it can be shorten as following

import formValidation from 'formvalidation/core/Core';

// Use the plugins
import Icon from 'formvalidation/plugins/Icon';
import Trigger from 'formvalidation/plugins/Trigger';
import Bootstrap from 'formvalidation/plugins/Bootstrap';

Update the MandatoryIcon guide

// Doesn't work
icon: new FormValidation.plugins.Icon(...),
mandatoryIcon: new FormValidation.plugins.MandatoryIcon(...),

// Work
mandatoryIcon: new FormValidation.plugins.MandatoryIcon(...),
icon: new FormValidation.plugins.Icon(...),

Duplicate Invalid Feedback messages in Bootstrap 5

Hello,

I have been using FormValidation plugin for a long time. I am having hard time with the Bootstrap 5.

FormValidation is adding multiple invalid-feedback in the form.

<div class="mb-4 form-group col-md-6">
<input type="hidden" name="activity[1][focus_area_has_subcategories]" id="activity1HiddenFocusAreaHasSubcategories" value="0">
<input type="hidden" name="activity[1][is_focus_area_other]" id="activity1HiddenFocusAreaOther" value="0">

<label class="form-label fw-bold" for="inputInputResourcesFocusArea1">
    <span class="activity-number">2.1</span>.1 Focus Area
</label>
<div class="form-check">
    <input class="form-check-input " name="activity[1][focus_area]" type="radio" value="1" id="activity1RadioFocusArea_1">
    <label class="form-check-label" for="activity1RadioFocusArea_1">
        Program &amp; Performance QM
    </label>
</div>
<div class="form-check">
    <input class="form-check-input " name="activity[1][focus_area]" type="radio" value="2" id="activity1RadioFocusArea_2">
    <label class="form-check-label" for="activity1RadioFocusArea_2">
        Fiscal &amp; Resource QM
    </label>
</div>
</div>
let fv = FormValidation.formValidation(
        document.getElementById('someFormSelector'),
        {
            fields: {
                'activity[1][focus_area]' : {
                    validators: {
                        notEmpty: {
                            message: 'Focus Area is required.'
                        },
                    }
                }
            },
            plugins: {
                bootstrap: new FormValidation.plugins.Bootstrap5({
                    rowSelector: '.mb-4',
                }),
                message: new FormValidation.plugins.Message(),
                trigger: new FormValidation.plugins.Trigger(),
                submitButton: new FormValidation.plugins.SubmitButton(),
                defaultSubmit: new FormValidation.plugins.DefaultSubmit(),
                sequence: new FormValidation.plugins.Sequence({
                    enable: true
                }),
            },
        }
    );

When form submit button is pressed, FormValidation adds two invalid-feedback block after stacked radio inputs. Can you please look into this?

Thank You.

Rutvij

verbose: false - not stop remote validator

Hi,

I want the field to be validated after 6 symbols and remote check to execute if the other passes.
But when I click a button and try to validate the form always see all errors and AJAX POST is sent.
my code:

    const frm_q = FormValidation.formValidation(
        document.getElementById('frm_q'), {
            fields: {
                ans: {
                    verbose: false,
                    threshold: 6,
                    validators: {
                        notEmpty: {
                        },
                        stringLength: {
                            min: 6,
                            max: 8
                        },
                        regexp: {
                            regexp: /^[A][A-Z0-9]{6}$/i,
                            message: 'REGEX'
                        },
                        remote: {
                            data: {
                                cid: 1,
                            },
                            url: '/api/check-code.php',
                            method: 'POST',
                            message: 'REMOTE'
                        }

                    }
                }
            },
            plugins: {
                bootstrap: new FormValidation.plugins.Bootstrap(),
                autoFocus: new FormValidation.plugins.AutoFocus(),
                icon: new FormValidation.plugins.Icon({
                    valid: 'fa fa-check',
                    invalid: 'fa fa-times',
                    validating: 'fa fa-refresh',
                }),
                trigger: new FormValidation.plugins.Trigger(),
            },
        }
    ).on('core.form.validating', function() {
        frm_qButton.innerHTML = 'CHEKING';
    });

    frm_qButton.addEventListener('click', function() {
        frm_q.validate().then(function(status) {
            // Update the login button content based on the validation status
            if (status === 'Valid') {
                    $("form#frm_user")[0].submit();
            } else {
                frm_qButton.innerHTML = 'TRY';
            }
        });
    });

I also try this - <form id="frm_q" data-fv-verbose="false">
with no success ..

Any idea?
and I use 1.8.1 full.min.js

Regards,
Tihomir

Exclude Plugin does not work with Recaptcha3 Plugin

When you have both plugins installed the Recaptcha3 does not work. Is this a bug or is there a way in the Exclude callback to ignore the Recaptcha field? I'm assuming it's not working because the recaptcha field is hidden.

revalidateField with Select2 doesn't work

Hello to everyone, I'm using code example of Select2 plugin to validate a multiple select field. I just want that the field has at least one element.

Here my code:

HTML:

                        <div class="form-group row">
                            <label for="roles" class="col-sm-3 col-form-label">{{ ucfirst(trans_choice("configurazione.ruoli",2)) }}</label>
                            <div class="col-sm-9">
                                <select name="roles[]" id="roles" class="form-control select2" multiple="">
                                    @foreach($ruoli as $ruolo)
                                        <option value="{{ $ruolo->id }}" {{ isset($utenti) ? (in_array($ruolo->id, $ruoliUtenti) ? "selected" : "") : "" }}>{{ $ruolo->name }}</option>
                                    @endforeach
                                </select>
                                <div class="invalid-feedback">{{ __("validation.filled", ['attribute' => trans_choice("configurazione.ruoli",1)]) }}</div>
                            </div>
                        </div>

JS:

document.addEventListener('DOMContentLoaded', function (e) {
    const userForm = document.getElementById('userForm');
    const rolesField = jQuery(userForm.querySelector('[name="roles"]'));

    const fv = FormValidation.formValidation(
        userForm,
        {

            locale: 'it_IT',
            localization: FormValidation.locales.it_IT,

            fields: {
                'roles[]': {
                    validators: {
                        callback: {
                            callback: function (input) {
                                // Get the selected options
                                const options = rolesField.select2('data');
                                return options != null && options.length < 1;
                            },
                        },
                    }
                },
            },
            plugins: {
                submitButton: new FormValidation.plugins.SubmitButton(),
                defaultSubmit: new FormValidation.plugins.DefaultSubmit(),
                bootstrap: new FormValidation.plugins.Bootstrap(),
                excluded: new FormValidation.plugins.Excluded(),
                // Show the feedback icons taken from FontAwesome
                icon: new FormValidation.plugins.Icon({
                    valid: 'fa fa-check',
                    invalid: 'fa fa-times',
                    validating: 'fa fa-refresh',
                }),
            }
        }
    );

    rolesField.select2().on('select2.change', function () {
        fv.revalidateField('roles[]');
    });
});

When I try to submit the form with empty value, it works, but after that, if I fill the field, the 'revalidateField' seems to not work.

I tried with:
fv.revalidateField('roles[]');
or
fv.revalidateField('roles');

Where is my error?

Feature Request: Enable declarative messages to be dynamic (i.e. via javascript)

Hi,

I was trying to figure out if thereโ€™s a way to make the message of a declarative validator dynamic to try and better address an issue that keeps surfacing in this site Iโ€™m working on.

In essence, depending on one or more settings, the label of a field can change. In such cases, I currently have to change the label as well as the validator message since the field name is repeated (a requirement in this site). Iโ€™d prefer to only have to change the label and have the validator pick up the corresponding label text to use in the message instead.

I have a function that already grabs the label text called fvValidatorGetFieldLabel. Iโ€™ve tried to use that but have since learned that the declarative message model only supports plain text. It would be really helpful if it supported javascript so that I could dynamically set the text of the message based on the corresponding label (or other conditions).

Would it be possible to add support for this?

Below is an possible use case scenario (see contents of data-fv-not-empty___message):

            <asp:Label ID="lblMeterSampleRate" CssClass="col-sm-2 control-label" runat="server">Meter Sample Rate</asp:Label>
            <div class="col-sm-4">
                <div class="input-group">
                    <span class="input-group-addon"><span class="fa fa-th-list"></span></span>
                    <asp:DropDownList ID="ddlMeterSampleRate" CssClass="form-control" runat="server" data-fv-row=".col-sm-4" data-fv-not-empty="true" data-fv-not-empty___message="fvValidatorGetFieldLabel(this) + ' is required.'" data-toggle="tooltip" title="Select how often FlexNet will read the meter data."></asp:DropDownList>
                </div>
            </div>

Declarative plugin: html5input validation doesn't work for dynamic fields

Hi,

I'm adding all my fields dynamically with addField method and I have the Declarative plugin enabled with html5input:true.
The html5 validation doesn't work at all.

After debugging it I found that the html5 validator options are set when the declarative plugin is loaded.
Problem: When the fields are added dynamically (afterwards) the element is not parsed and no validators added.

I did a fix on my side which is the following:

`const declarativeOptions = oFormValidator.getPlugin('declarative').parseElement(myElement);

options.validators = {
callback : {
callback: myCallback,
},
...declarativeOptions.validators
};

oFormValidator.addField(myFieldName, options);`

So, I'm manually parsing each element and adding the validators returned my the parseElement() to the options.
This is kinda of an hack. Would be nice if you could fix it on your side, this should be done automatically when a field is added dynamically.

Thanks.

Bug (HOT) with Trigger plugin: String.prototype methods conflict with field names

In prepareHandler method I found a big problem.

 } else if (!!this.opts.event && !!this.opts.event[field]) {
    events = this.opts.event[field].split(' ');
} else if (

In my case I have input with name="link" and error _this2.opts.event[e].split is not a function occured.
From research codebase I found problem:
It's not safe to check this way !!this.opts.event[field].
Because String.prototype have old 'link' method and that can me accessed from 'xxx'.link.

Hotfix:

 } else if (!!this.opts.event && !!this.opts.event[field] && ['boolean', 'string'].indexOf(typeof _this2.opts.event[e]) !== -1) {

or minimum not allow functions

 } else if (!!this.opts.event && !!this.opts.event[field] && typeof _this2.opts.event[e] !== 'function' ) {

resetForm() not resetting Select2 validation message

Hello,
I have several Select2 fields on Bootstrap 5 modal form and I can't clear the validation error messages of it. I was trying with resetForm(true) and resetField('Select2-field', true) and none of them seems to work. All the other inputs messages are cleared but Select2.
I am using the latest version 1.9.0.

BUG: .destroy() & Bootstrap5 plugin loses the border radius of input groups

Even if this was fixed in v 1.8, this still here after I call .destroy()
Because message container after destroy was removed, but classname has-validation not
This cause stop work this stylesheet

.input-group.has-validation>.dropdown-toggle:nth-last-child(n+4), .input-group.has-validation>:nth-last-child(n+3):not(.dropdown-toggle):not(.dropdown-menu) {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}

Bootstrap 5 row selector

I'm using bootstrap 5 plugin. There is a rowSelector: ".row", which causes errors. If there is no row class it throws error and crashes application.
There is plenty of examples where there will be no row class.
For example form-floating variation: https://getbootstrap.com/docs/5.1/forms/floating-labels/

I know (now :/) that we can change row selectors, but if there is a good error message I can get to it much sooner :)

EDIT:
Maybe something like this would be better:

       rowSelector: function (field, ele) {
          if (ele.parentElement && ele.parentElement.classList && ele.parentElement.classList[0]) {
            return '.' + ele.parentElement.classList[0];
          }
          return '.row';
        }

File validator maximum number of files not work

When I select files with the number of files under maximum files it works fine. Then I add another files with the number of files I selected under the maximum file. And the number of all the files that i've selected exceeds the maximum number of file. But it returns a valid value, how to change it to false value?

This is my code

'file[]': {
    validators: {
        notEmpty: {
            message: 'File field is required'
        },
        file: {
            maxFiles: 3,
            type: 'image/jpeg,image/png',
            message: 'Max upload 3 files'
        }
    }
},

Checkbox not validated on resubmission

When the Trigger plugin is not used and form has checkbox inputs, the form does not revalidate upon resubmission.
This seems to only happen to checkbox inputs. Plugins used for Bootstrap, SubmitButton and DefaultButton.

Revalidation works correctly when manually calling fv.validate().

updateValidatorOption issue

I have a problem with the function updateValidatorOption()

Even this simple code does not work unfortunately:

var validation = FormValidation.formValidation(
  passwordForm,
  {
    fields: {
      current_password: {
        validators: {
          notEmpty: {
            message: 'Current Password is required'
          }
        }
      }
    }
  }
);
validation.validate().then(function (status) {
  validation
  .updateValidatorOption("current_password", 'blank', 'message', 'test')
  .updateFieldStatus("current_password", 'Invalid', 'blank');
});

I get the following error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'message')

fv.destroy() => Uncaught Error: The plguin ___frameworkMessage is registered

What is the best way to re-init Declarative plugin rules after html5 attributes changed?
I have one global initializer for all own forms

/* global initFormValidation */
$(function () {
  // Allow configure localization globally
  const getFormValidationLocalizationConfig = () => {
    return (
      window.formValidationLocalizationConfig || {
        locale: 'en_US',
        localization: FormValidation.locales.en_US,
      }
    );
  };

  const getFormValidationBaseConfig = () => ({
    plugins: {
      trigger: new FormValidation.plugins.Trigger({
        event: 'input', // By default, the field will be validated automatically when the input event is triggered (but that is not true and this plugin helps)
      }),
      declarative: new FormValidation.plugins.Declarative({
        html5Input: true, // the Declarative plugin will automatically enable the validators for the following input type and HTML 5 attributes, see: https://formvalidation.io/guide/examples/using-html-5-inputs-and-attributes/
      }),

      bootstrap: new FormValidation.plugins.Bootstrap5({
        rowSelector: '.fv-row',
        // eleInvalidClass: '',
        eleValidClass: '',
      }),
      // aria: new FormValidation.plugins.Aria(),
      // sequence: new FormValidation.plugins.Sequence({
      //   enabled: true,
      // }),
      autoFocus: new FormValidation.plugins.AutoFocus(),
    },
  });

  function initFormValidation(form) {
    function init() {
      return FormValidation.formValidation(form, {
        ...getFormValidationLocalizationConfig(),
        ...getFormValidationBaseConfig(),
      });
    }

    let fv = form.fv;

    const reinit = () => {
      if (fv) {
        fv.destroy();
      }
      fv = init();
    };

    reinit();

    form.fv = fv;

    $(form).data({
      fv,
      init: reinit,
      reinit,
    });

    return fv;
  }

  // Expose to global scope
  window.initFormValidation = initFormValidation;

  // Init FormValidation instance on initial rendered forms with .js-form-validate
  (() => {
    var $forms = $('.js-form-validate');
    if ($forms.length === 0) return;

    $forms.each(function () {
      initFormValidation(this);
    });
  })();

  // Handle submit all forms with .js-form-validate
  // If form is dynamically created, init FormValidation instance on it
  $(document).on('submit', '.js-form-validate', async function (e) {
    e.preventDefault();

    const $form = $(this);

    let fv = $form.data('fv');

    if (!fv) {
      fv = initFormValidation(this);
    }

    // Validate form before submit
    const status = await fv.validate();
    if (status == 'Valid') {
      $form.trigger('form.awaitSubmit');
    }
    return false;
  });
});

Then, I change on the fly element max attribute
$('input').attr('max', 100);
Declarative don't see this change and still use old max value.
For this purpose I call initFormValidation($('input').closest('form')[0])
That function just call fv.destroy(); then re-initialize validation FormValidation.formValidation(form, ...) again.
But error appears FormValidation.min.js:1 Uncaught Error: The plguin ___frameworkMessage is registered
After error validation messages not appear.

Please help me!

Cannot validate dynamically added input fields in a wizzard form

I have used the wizard example without issues on step 1 but on step two I get an error Cannot read property 'classList' of null.
This is how step 2 looks like:

        // Step 2
        _validations.push(FormValidation.formValidation(
            _formEl,
            {
                fields: {},
                plugins: {
                    trigger: new FormValidation.plugins.Trigger(),
                    bootstrap: new FormValidation.plugins.Bootstrap()
                }
            }));

Then I generate a hidden input field dynamically and adds it to the DOM inside the second step wizzard:

<input type="hidden" id="example_documents_businessRegistration" name="example[documents][businessRegistration]" class="data-not-empty form-control form-control-solid form-control-lg" value="abcd">

Once this is added I trigger an event that adds this field to the second step on the wizard fields:

 // Listen to new hidden input fields when inserted by the dropzone upload script
$('#form').on('newHiddenField', function (event, newHiddenInputField) {
        addFieldValidation(newHiddenInputField);
 });
// if the field is multiple and has a protoype: use the prototype to create new hidden field
const addFieldValidation = function (newHiddenInputField) {
    let fieldName = newHiddenInputField.attr('name');
    console.log(newHiddenInputField.attr('name'));
    const notEmptyValidators = {
        validators: {
            notEmpty: {
                message: 'Field is required'
            }
        }
    };
    console.log('start add field');
    _validations[1].addField(fieldName, notEmptyValidators);
    console.log('add field end');
}
 // Add an event for creating a validation for the field if needed
 $('#kt_form').trigger('newHiddenField', [newHiddenInputField]);

The _validations[1].addField(fieldName, notEmptyValidators); is not working :(
Any help please?

Set default locale

// Set the default locale
locale: 'en_US',
localization: FormValidation.locales.en_US,

I want to set this initially for all validation instances that be created in future?
A don't found any method for this

How can i send data via ajax

on('core.form.valid', function(e) {
            FormValidation.utils.fetch("{{ lRoute('myroute.add') }}", {
            method: 'POST',
            params : {
            data : form.serialize(); // unable to make it working it took hours , how can i send data like this , the form data
}
            
            }).then(function(response) {
                // Depending on the response from server, you can display a notification
                // to let user know if the form is sent successfully
            });

Email validation not reset on keyup?

Hello!

There might be an issue with the demo form.

Repro

  1. Type a valid email
  2. Delete a character to make invalid while the field is still focussed

Expected

Validation fails, either on keyup or blur

Actual

email validation failure

Multiple error messages for file upload rules

<input 
type="file" 
name="uploadphoto" 
data-fv-file="true" 

data-fv-file___max-size="2000000"

data-fv-file___extension="jpeg,png,gif" 
data-fv-file___type="image/jpeg,image/png,image/gif"
>

In this example input, there are two validation rules like

  1. Checking file size
  2. Checking file type

As there is only one message attribute called data-fv-file___message , how can I display error message for both file size and type validations?

E.g
If user upload a file that bigger than 2000000 byets, it will show a message like Max file size is 2 MB.

If user upload a file that is not image, it will show a message like Only jpeg,png,gif extensions are allowed.

resetForm() not resetting form validation

Have been trying to use the form validation when i 'cancel' the form to reset all validation and clear the form. Clearing the form inputs works but the resetForm() does nto seem to be working for the plugin. I have followed your guide just wondering what im doing wrong? Function wizardReset is called by a "Cance" Button

const fv = FormValidation.formValidation(
            document.getElementById('kt_form'),
            {
                fields: {
                    parcel_name: {
                        validators: {
                            notEmpty: {
                                message: 'Name is required'
                            },
                        }
                    },

                    weight: {
                        validators: {
                            notEmpty: {
                                message: 'Weight is required'
                            },
                            numeric: {
                                message: 'The weight is not a valid number'
                            },
                            greaterThan: {
                                inclusive: false,
                                message: 'The weight must be greater than zero',
                                min: 0
                            }
                        }
                    },

                    height: {
                        validators: {
                            notEmpty: {
                                message: 'Height is required'
                            },
                            numeric: {
                                message: 'The height is not a valid number'
                            },
                            greaterThan: {
                                inclusive: false,
                                message: 'The height must be greater than zero',
                                min: 0
                            }
                        }
                    },

                    depth: {
                        validators: {
                            notEmpty: {
                                message: 'Depth is required'
                            },
                            numeric: {
                                message: 'The depth is not a valid number'
                            },
                            greaterThan: {
                                inclusive: false,
                                message: 'The depth must be greater than zero',
                                min: 0
                            }
                        }
                    },

                    width: {
                        validators: {
                            notEmpty: {
                                message: 'Width is required'
                            },
                            numeric: {
                                message: 'The velue is not a valid number'
                            },
                            greaterThan: {
                                inclusive: false,
                                message: 'The width must be greater than zero',
                                min: 0
                            }
                        }
                    },
                },
                plugins: {
                    trigger: new FormValidation.plugins.Trigger(),
                    // Bootstrap Framework Integration
                    bootstrap: new FormValidation.plugins.Bootstrap(),
                    // Validate fields when clicking the Submit button
                    submitButton: new FormValidation.plugins.SubmitButton(),
                    // Submit the form when all fields are valid
                    defaultSubmit: new FormValidation.plugins.DefaultSubmit(),

                }
            }
        );

        function wizardReset() {
            fv.resetForm(true);
            $("#kt_form").trigger('reset');
            let wizard = new KTWizard('kt_wizard');
            wizard.goTo(1);
        }

How to make it work with bootstrap select plugin

This si what i have so far but cant get it to work ๐Ÿ‘ `document.addEventListener('DOMContentLoaded', function(e) {
const mydropzone = document.getElementById('mydropzone');

const RoleIdField = jQuery(mydropzone.querySelector('[name="roleId"]'));    

const fv = FormValidation.formValidation(mydropzone, {    
       
    
        fields: {
            first_name: {
                validators: {
                    notEmpty: {
                        message: 'First Name is required'
                    },                        
                    regexp: {
                        regexp: /^[a-zA-Z]+$/,
                        message: 'First Name can only consist of alphabetical characters'
                    }
                }
            },
            last_name: {
                validators: {
                    notEmpty: {
                        message: 'Last Name is required'
                    },                        
                    regexp: {
                        regexp: /^[a-zA-Z]+$/,
                        message: 'First Name can only consist of alphabetical characters'
                    }
                }
            },
            roleId: {
                validators: {
                    notEmpty: {
                        message: 'Please select a Role'
                    },  
                }
            },
           
        },
        plugins: {
            trigger: new FormValidation.plugins.Trigger(),
            bootstrap: new FormValidation.plugins.Bootstrap(),
            submitButton: new FormValidation.plugins.SubmitButton(),
            icon: new FormValidation.plugins.Icon({
                valid: 'fa fa-check',
                invalid: 'fa fa-times',
                validating: 'fa fa-refresh'
            }),
        }
    }
);

});

$('#roleId').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
// Revalidate the color field when an option is chosen
fv.revalidateField('roelId');
});
`

New Dutch VAT numbers are validated as incorrect

In Januari the Dutch Government issued a new format for VAT numbers to one-man companies. Right now if these are put in to the validation they will be marked as an incorrect VAT number, I.E NL002014005B30

Are we doing something wrong, or are these not implemented yet?

Placeholders in declarative messages - how?

Hi
I want this

<input type="number" required
min="1"
max="20"
data-fv-greater-than___message="Min %(value)"
data-fv-less-than___message="Max %(value)"

Why? What is min & max is changed somewhere or somewhen? We need to manually hardcode values in messages?
Or some workaround about this? Maybe another syntax now works for this purpose?
I don't want fully dynamic custom values, but for me is important to have access to:

  • attribute value (in example case - attributes have concrete values)

declarative plugin html5input: mandatory data-fv-string-length___message

Hi,

I'm using the declarative plugin with html5input: true.
Couldn't find why is the data-fv-string-length___message attribute mandatory. In my case I don't want to show an error message for some fields (just red border).
If the data-fv-string-length___message is not defined the validation of html5 fields simply doesn't work, from my point of view this is a bug. Seems that the validator stuck on "validating" state.

Of course I can define the data-fv-string-length___message attribute empty, but when dealing with dynamic fields and bigger forms, this is a mess.

I did a fix on my side, when preparing the options pass on to addField():


const oOptions = oFormValidator.getPlugin('declarative').parseElement(oFormElement);
      Object.keys(oOptions.validators).forEach(sValidator => {
        if (
              oOptions.validators[sValidator].enabled === true
            && oOptions.validators[sValidator].message === undefined
        ) {
          oOptions.validators[sValidator].message = ' ';
        }
      });

I'm simply setting the message to empty so that the validator work, otherwise message is undefined and validator doesn't work.

Do you think it make sense to fix this behaviour on your side?

Thanks!

Decarative Inclusive doesnt seem to work on greater than, less than

data-fv-between="true" data-fv-between___message="Enter value between 1 and 200" data-fv-between___inclusive="false" data-fv-between___min="1" data-fv-between___max="200"

According to the docs this should force a greater than (but not equal to) 1 and less than (but not equal to) 200

However on the greater than, less than and between validators this isnt working from a declarative implementation. The above allows entry of 1 or 200 and validates as true

Currency validation

Hi,

I would like to use a validator for a text input field containing a currency string. The value will be something like: $123,456

The existing numeric and integer validators are almost good enough, as they can handle thousands separator and decimals, but it can't cope with the dollar sign in front.

Would you consider adding a "prefix" option to the integer and/or numeric validators, to allow us to specify a currency sign?

Or add a new validator specifically for currency strings?

Thanks

PasswordStrength in Vue.

I am trying to use PasswordStrength in metronic_v7.1.7 vue demo1.

Added the import:

import PasswordStrength from "@/assets/plugins/formvalidation/dist/es6/plugins/PasswordStrength";

And in plugins:

  plugins: {
    trigger: new Trigger(),
    bootstrap: new Bootstrap(),
    passwordStrength: PasswordStrength({
      field: "password",
      message: "The password is weak",
      minimalScore: 3
    })
  }

But it does not work. Did I miss something?

Can you add an example of using PasswordStrength with Vue?

Thanks.

File extensions validation with Declarative doesn't seem to work

Version
Formvalitation - v1.6.0
Bootstrap plugin - v1.6.0

I made an example repo here to test the issue.

In above example repo, you'll see Formvalidation doesn't validate file extensions, I can still browse or add any extension.

<input 
    class="form-control" 
    type="file" 
    name="user_file" 
    id="user_file" 
    data-field-type="file"
    data-fv-file___extension="jpg,png,pdf"
    data-fv-file___type="image/jpeg,image/png,application/pdf"
    data-fv-file___message="Only jpg,png,pdf extensions are allowed"
>

Showing custom message returned from server not trigger Autofocus

Hi
I used example from the docs
https://formvalidation.io/guide/examples/showing-custom-message-returned-from-server/
Also I use Autofocus plugin.

After

        // Update the message option
        .updateValidatorOption(
            field, 'blank', 'message', response.fields[field]
        )
        // Set the field as invalid
        .updateFieldStatus(field, 'Invalid', 'blank');

I expect that the field to be autofocused because it is invalid, but nothing happened.
For large forms this is bad behavior.

  this.core
      .on('core.form.invalid', this.invalidFormHandler)
      .registerPlugin(this.fieldStatusPluginName, new FieldStatus());

Maybe somehow 'core.form.invalid' is not emitted when you use updateFieldStatus with blank?
Help me how to fix that?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.