Field selector

Validating field determined by a CSS selector

In the Usage page, we know that it's possible to declare the validator rules for field via its name attribute:


...
document.addEventListener('DOMContentLoaded', function(e) { FormValidation.formValidation( document.getElementById('loginForm'), { fields: { username: { validators: { ... } }, } } ); });

But in reality, there're cases that it's not possible to use the name attribute for the field.

For example, assume that you have to fill in a payment form containing sensitive data such as the credit card number, its expiration date, .etc. These fields are nameless elements. How we can apply the validation rules for them?

Tip

By not using the name attribute for sensitive fields, we can prevent them from sending to the server when the form is submitted.

Fortunately, FormValidation provides the selector option to support indicating fields via a CSS selector:


...
document.addEventListener('DOMContentLoaded', function(e) { FormValidation.formValidation( document.getElementById('purchaseForm'), { fields: { ccNumber: { // The credit card number field can be retrieved // by [data-stripe="number"] attribute selector: '[data-stripe="number"]', validators: { notEmpty: { ... }, creditCard: { ... } } }, }, } ); });

The following example shows how to use this option to validate a a standard Stripe payment form.

All fields for filling the credit card information don't have the name attribute. Instead, they use the data-stripe attribute which are defined by Stripe. The Stripe API then will collects the credit card data from fields using this attribute.