notEmpty validator

Check if the value an is empty string

Options

Using with form field

The HTML attributes are used to set the validator options via the Declarative plugin

Name HTML attribute Type Description
message data-fv-not-empty___message String The error message

Use with select element

If you want a select element to be required, you have to set value="" for the option which is treated as empty one:



Using with JavaScript module


// You might need to change the importing path
import notEmpty from 'formvalidation/validators/notEmpty';

const result = notEmpty().validate({
    value: ...,
    options: {
        message: ...,
    },
});
/*
result is an object of
{
    valid: true or false,
    message: The error message
}
*/

Tip

The MandatoryIcon plugin is useful when you want to display the mandatory icon for required fields

Basic example

In the following form, user is asked to enter the full name.

HTML5 example

When the Declarative plugin is used, the notEmpty validator will be turned on automatically if the input uses HTML 5 required attribute.

Trim the value

The notEmpty validator does not remove the blank spaces at the beginning and ending of the value. It means that a string like ' ' is treated as valid.

If you want to prevent this, then use the Transformer plugin to trim the value before validating it.

Using with WYSIWYG editor

Most of WYSIWYG (What You See Is What You Get) editors generate some HTML tags for an empty string. So, basically, you can't use notEmpty validator to validate a text area which uses a WYSIWYG editor.

Instead, use the callback validator to get the raw HTML string, and check if it's the default value generated by the editor, then it's empty field.

The following example demonstrates how to do it with the TinyMCE editor.

Module example

The following snippet shows how to use the notEmpty validator with JavaScript module:


// You might need to change the importing path
import notEmpty from 'formvalidation/validators/notEmpty';

const res1 = notEmpty().validate({
    value: 'John Smith',
    options: {
        message: 'The name is required',
    },
});
// res1.valid === true

const res2 = notEmpty().validate({
    value: '',
    options: {
        message: 'The name is required',
    },
});
// res2.valid === false

const res3 = notEmpty().validate({
    value: '   ',
    options: {
        message: 'The name is required',
    },
});
// res3.valid === false

Related validators

The following validators are similar to this one and might be useful to you.

Name Description
stringLength Validate the length of a string