-1

So I have this field input in my UI, I need it to throw an error if it is left blank, but it is not. This is my code

<div class="slds-text-heading_medium slds-align_absolute-center">
        <lightning:input aura:id="matrixName" name="Matrix Name" maxlength="80"
                         label="Matrix Name" placeholder="Matrix Name" />
        <aura:if isTrue="{!not(empty(v.inputError))}">
            {!v.inputError}
        </aura:if>
    </div>

My controller

doCreateMatrix: function (component) {
    var matrixInput = component.find("matrixName");

    if (!matrixInput) {
        console.log("matrixName has not been found");
        return;
    }

    var matrixName = matrixInput.get('v.value');

    if (!matrixName || matrixName.trim().length === 0) {
        //Handle BLANK matrixName
        component.set("v.inputError", "Name cannot be blank");
        return;
    }
  • 3
    Why not just use required="true"? The component can validate itself. – sfdcfox Mar 27 at 19:32
  • I added the the condition required="true", should I remove the aura:if because it is still not showing my error message, I added what I have in my controller – Deja Bond Mar 27 at 19:43
1

The standard method is to let the component validate itself:

    <lightning:input aura:id="matrixName" name="Matrix Name" maxlength="80"
                     label="Matrix Name" placeholder="Matrix Name" 
                     required="true" />

This will also add the required askerisk (a red *) to the field's label, indicating it is required.

In your code, make sure you check validity before submitting data to the server:

var matrixField = component.find("matrixName");
matrixField.showHelpMessageIfInvalid();
if(!matrixField.checkValidity()) {
  // Optional message if you want
  alert("Please fill out the required field."); 
  return; // Don't continue past this point
}
  • Yea for some reason, the alert is not appearing on screen, I have exactly what you have – Deja Bond Mar 27 at 20:01
  • I think I discovered why, Ill share shortly – Deja Bond Mar 27 at 20:21
  • i had to add the attribute to my original code <aura:attribute name="inputError" type="String" default="" /> – Deja Bond Mar 27 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.