[SalesForce] Lightning:input mandatory=”True” not fired on button click

I have a Lightning component with input fields with some mandatory.

At the end of the page, I have button when clicked, gathers all the info entered and creates a record in back end.

I assumed when I use, mandatory="True" on input filed, upon button click it will throw error messages and force user to fill in.

But it doesn't throw errors and send null data to apex class.

Example:
Lightning cmp:

<div>
                                    <lightning:select name="Type" label="C Type:" required="True" aura:id="Type" >
                                        <option value="">Choose One</option>
                                        <option value="1">One</option>
                                        <option value="2">Two</option>
                                        <option value="3">Three</option>
                                        <option value="4">Four</option>
                                        <option value="5">Five</option>
                                    </lightning:select>
                                </div>
<lightning:button variant="brand" class="buttoncss slds-float_right" label="Create" onclick="{!c.createRecord}"/>

Controller:

createRecord: function(component, event, helper) {


        var filters = {};
filters.param1 = component.find("Type").get("v.value");

//Pass this filters to apex

When The drop down is left empty, upon button click null is passed to apex.

What am I missing here to fire mandatory field error message?

Best Answer

You'll want to read Validating Fields for more information, but generally speaking, you need to check the validity before sending the data off to the server. Nothing in the framework prevents calling the server while in an error status.


createRecord: function(component, event, helper) {
  if(component.find("Type").get("v.value")) {
    // send to server
  } else {
    component.find("Type").set("v.errors", [{message:"A value is required"}]);
  }
}
Related Topic