Newer Version Available

This content describes an older version of this product. View Latest

Validating Fields

You can validate fields using JavaScript. Typically, you validate the user input, identify any errors, and display the error messages.

Default Error Handling

The framework can handle and display errors using the default error component, ui:inputDefaultError. The following example shows how the framework handles a validation error and uses the default error component to display the error message.

Component source

1swfobject.registerObject("clippy.codeblock-0", "9");<aura:component>
2    Enter a number: <ui:inputNumber aura:id="inputCmp"/> <br/>
3    <ui:button label="Submit" press="{!c.doAction}"/>
4</aura:component>
5

Client-side controller source

1swfobject.registerObject("clippy.codeblock-1", "9");{
2    doAction : function(component) {
3        var inputCmp = component.find("inputCmp");
4        var value = inputCmp.get("v.value");
5
6        // is input numeric?
7        if (isNaN(value)) {
8            // set error
9            inputCmp.setValid("v.value", false);
10            inputCmp.addErrors("v.value", [{message:"Input not a number: " + value}]);
11        } else {
12                // clear error
13                inputCmp.setValid("v.value", true);
14        }
15    }
16}
17

When you enter a value and click Submit, an action in the controller validates the input and displays an error message if the input is not a number. Entering a valid input clears the error. The controller invalidates the input value using setValid(false) and clears any error using setValid(true). You can add error messages to the input value using addErrors().