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 a field via its
name
attribute:
<form id="loginForm" method="POST">
<input type="text" name="username" />
...
</form>
<script>
document.addEventListener('DOMContentLoaded', function(e) {
FormValidation.formValidation(
document.getElementById('loginForm'),
{
fields: {
username: {
validators: {
...
}
},
}
}
);
});
</script>
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?
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:
<form id="purchaseForm" method="POST">
<input type="text" [data-stripe="number" ] />
...
</form>
<script>
document.addEventListener('DOMContentLoaded', function(e) {
FormValidation.formValidation(
document.getElementById('purchaseForm'),
{
fields: {
ccNumber: {
selector: '[data-stripe="number"]',
validators: {
notEmpty: {
...
},
creditCard: {
...
}
}
},
},
}
);
});
</script>
The following example shows how to use this option to validate a standard
Stripe payment form.
All fields for filling in the credit card information don't have the name
attribute. Instead, they use the data-stripe
attribute which is defined by Stripe. The Stripe API then will collect the credit card data from fields using this attribute.