---
schema_version: "1"
id: 066cd0e858c80f90851a9f8fdf69de09c86f70e91a1f60f681aeecb300dd8410
title: Validating Fields
collection: developer
version: current
locale: en-us
portal_url: https://docs.salesforce.com/developer/current/en-us/platform/aura-platform/guides/aura/js/js-validate-fields.md
canonical_url: https://developer.salesforce.com/docs/platform/aura-platform/guide/js-validate-fields.html
source_site: developer.salesforce.com
content_type: documentation
content_hash: 7f0e222542e01433bc89a8adc2b4ad6b67d6fd4661f0400841c1d97d4f6cf228
products:
  - Lightning Aura Components Developer Guide
  - Platform Developer Content
---

# Validating Fields

Validate user input, handle errors, and display error messages on input fields.

Built-in field validation is available for the base components discussed in [Creating a Form](https://developer.salesforce.com/docs/platform/aura-platform/slds/lightning-base-form.md).

Base components simplify input validation by providing attributes to define error conditions, enabling you to handle errors by checking the component’s validity state. For example, you can set a minimum length for a field, display an error message when the condition is not met, and handle the error based on the given validity state.

Most of the base components provide attributes and methods to enable different ways to validate input.

**note:** Refer to the [Component Library](https://developer.salesforce.com/docs/component-library/) for component examples, specification, and documentation.

**Require a field:** When you set `required="true"`, the field is invalid when a user interacts with it but does not make a selection or enter an input.

**Specify a type**

A `lightning:input` field that expects a certain data type is invalid if an incorrect data format is entered. For example, the `email` type on `lightning:input` expects an email address and the `number` type expects a number.

**Specify a criteria**

A `lightning:input` field that specifies a certain criteria or attribute, `max`, `min`, `pattern`, and so on, is invalid if the criteria isn’t met. You can provide a custom error message using attributes like `messageWhenValueMissing`, when it’s available on the component.

**Check field validity**

The `validity` attribute on the base components returns the validity states of an input. This attribute is based on the ValidityState object from the Web API. For example, you want to check if a field is valid when a user removes focus from the field.

```nolang
<lightning:input name="input" aura:id="myinput" label="Enter some text" onblur="{! c.handleBlur }" />
```

If all constraint validations are met, the field returns true .

```html
handleBlur: function (cmp, event) {
    var validity = cmp.find("myinput").get("v.validity");
    console.log(validity.valid); //returns true
}
```

**Report field validity**

To programmatically set and display an error message on a field, use the `setCustomValidity()` and `reportValidity()` methods available on the base components. For more information, see the [lightning:input documentation](https://developer.salesforce.com/docs/component-library/bundle/lightning:input/documentation).

## Prevent Invalid Fields from Getting Submitted

In [Creating a Form](https://developer.salesforce.com/docs/platform/aura-platform/slds/lightning-base-form.md) we implemented a basic form with built-in validation for required fields and specific types. Let’s customize the submission behavior such that the form displays errors on invalid fields. Customized behavior is useful if a user tries to submit an empty form and to identify errors in a field.

```javascript
({
    handleCreateContact: function(component, event) {
        var allValid = component.find('contact').reduce(function (validSoFar, inputCmp) {
            inputCmp.reportValidity();
            return validSoFar && inputCmp.checkValidity();
        }, true);

        if (allValid) {
        /******** Insert code from "Creating a Form" topic ********/
        var saveContactAction = component.get("c.createContact");
            saveContactAction.setParams({
                "contact": component.get("v.newContact")
            });
        
        // Configure the response handler for the action
            saveContactAction.setCallback(this, function(response) {
                var state = response.getState();
                if(state === "SUCCESS") {
                    component.set("v.message", "Contact created successfully");
                }
                else if (state === "ERROR") {
                    console.log('Problem saving contact, response state: ' + state);
                }
                else {
                    console.log('Unknown problem, response state: ' + state);
                }
            });
 
            // Send the request to create the new contact
            $A.enqueueAction(saveContactAction);
            /******** End code from "Creating a Form" topic ********/
        } else {
            alert('Please update the invalid form entries and try again.');
        }
        
    },
})
```


## Example

The [Aura Components Basics Trailhead module](https://trailhead.salesforce.com/content/learn/modules/lex_dev_lc_basics) walks you through building a form for creating an expense record.

## Field Validation Considerations

Client-side field validation provides an initial check for user data before submitting it to the server. Implement your own server-side validation to ensure that user data is saved in the expected format. Consider the following guidelines.

**Start with Lightning Data Service**

When working with Salesforce data, we recommend that you use the `lightning:recordForm`, `lightning:recordEditForm`, `lightning:recordViewForm`, or `force:recordData` base components. They are built on [Lightning Data Service](https://developer.salesforce.com/docs/platform/aura-platform/data-service/data-service.md), which ensures data consistency, while handling sharing rules and field-level security for you. The components also provide field validation and error handling.

**Enforce data integrity**

For data integrity, enforce it at the lowest level possible. For example, specifying `required="true"` on the base components is only cosmetic. Enforce the field as required in the field definition. See [Require Field Input to Ensure Data Quality](https://help.salesforce.com/articleView?id=fields_about_universally_required_fields.htm).

**Consider validation rules**

Define [validation rules](https://help.salesforce.com/articleView?id=fields_about_field_validation.htm) to verify that the data a user enters in a record meets the standards you specify before the user can save the record. You can retrieve the error that’s returned by a validation rule using [`response.getError()`](https://developer.salesforce.com/docs/platform/aura-platform/ref-jsapi/ref-jsapi-action-geterror.md). If you don’t handle the error, the form submission fails silently.

Alternatively, use a base component built on Lightning Data Service to automatically display the validation rule error on a field. For example, you can define a validation rule that enforces an email address to contain `@example.com`. The field displays the error message if the validation rule fails.

