stringLength validator

Validate the length of a string

Options

Using with form field
The HTML attributes are used to set the validator options via the Declarative plugin
(* denotes a required option)
NameHTML attributeTypeDescription
max *data-fv-string-length___max or maxlengthNumberThe maximum length
messagedata-fv-string-length___messageStringThe error message
min *data-fv-string-length___min or minlengthNumberThe minimum length
utf8Bytesdata-fv-string-length___utf8-bytesBooleanEvaluate string length in UTF-8 bytes. Default to false
trimdata-fv-string-length___trimBooleanIndicate the length will be calculated after trimming the value or not. Default to false
At least one of min and max options is required.
Using the ES6 module
// You might need to change the importing path
import { stringLength } from '/vendors/@form-validation/cjs/validator-string-length';
const result = stringLength().validate({
value: ...,
options: {
max: ...,
message: ...,
min: ...,
utf8Bytes: ...,
trim: ...,
},
});
/*
result is an object of
{
valid: true or false,
message: The error message
}
*/
Using the npm package
  • Install the validator package:
$ npm install @form-validation/validator-string-length
  • Use the stringLength validator:
import { stringLength } from '@form-validation/validator-string-length';
const result = stringLength().validate({
value: ...,
options: {
max: ...,
message: ...,
min: ...,
utf8Bytes: ...,
trim: ...,
},
});

Basic example

In the following form, the Full name and Bio fields must be less than 50 and 200 characters respectively.
Basic example

HTML5 Example

When the Declarative plugin is used, the stringLength validator will be turned on automatically if the input uses HTML 5 maxlength or minlength attribute.
HTML5 example

NPM package example

The following snippet shows how to use the stringLength validator with the npm package:
import { stringLength } from '@form-validation/validator-string-length';
const res1 = stringLength().validate({
value: '123456',
options: {
max: 10,
message: 'The input has to be less than 11 characters',
},
});
// res1.valid === true
const res2 = stringLength().validate({
value: '1234567890♥',
options: {
min: 5,
max: 10,
message: 'The input has to be between 5 and 10 characters long',
},
});
// res2.valid === false

See also

Changelog

v2.1.0
  • The validator doesn't work properly if the message property isn't defined
v2.0.0
  • Add the npm package
v1.8.0
  • The stringLength validator doesn't increase or decrease the number of characters in the error message
v1.6.0
  • Fixed an issue that the max and min options aren't passed to the placeholder message