1

I have a Custom modal with lightning-input and lightning-input-field on click on save button have to validate the input fields is mandatory.

lightning-input-field is pick list values

For lightning-input by adding the below code It validate me in client side and shows the error box adding classslds-has-error.

 const allValid = [  ...this.template.querySelectorAll("lightning-input")
].reduce((validSoFar, inputCmp) => {
 inputCmp.reportValidity();
 return validSoFar && inputCmp.checkValidity();
 }, true);

for lighting -input fields even though the pick list value is not selected, when we click save button the controller method createParentGuardian is called, Client Side validation is not happening. required parameter is added in lighting -input fields.

Can you please help me on this.

HTML

 <section role="dialog" tabindex="-1" class="slds-modal slds-fade-in-open slds-modal_large"
                            aria-labelledby="modal-heading-01" aria-modal="true"
                            aria-describedby="modal-content-id-1">
                            <div class="slds-modal__container" style="width: 50%;">

                                <div class="slds-modal__content slds-p-around_medium"
                                    id="modal-content-id-1-addparent" style="height: 65%;">

                                    <lightning-record-edit-form object-api-name="Contact">
                                        <div class="demo-only demo-only--sizing slds-grid slds-wrap">
                                            <div class="slds-size_2-of-4 ">
                                                <div class="slds-text-align_center slds-m-around_x-small">
                                                    <lightning-input label="First Name" value={firstname}
                                                        onchange={handleChange} name="firstname"
                                                        message-when-value-missing="First Name is Missing" required>
                                                    </lightning-input>
                                                </div>
                                            </div>

                                            <div class="slds-size_2-of-2">
                                                <div class="slds-text-align_center slds-m-around_x small">
                                                    <lightning-input-field field- name="Student_Relation__c"
                                                        onchange={handleChange} name="relationship" required>
                                                    </lightning-input-field>

                                                </div>
                                            </div>

                                        </div>
                                    </lightning-record-edit-form>

                                </div>
                                <footer class="slds-modal__footer">
                                    <lightning-button label="Cancel" variant="neutral"
                                        onclick={closeStudentParentModal}>
                                    </lightning-button>
                                    &nbsp;&nbsp;&nbsp;&nbsp;
                                    <lightning-button type="submit" variant="brand" value="AddParent"
                                        name="AddParent" label="Save" onclick= 
                                    {handleonClickParentSave}>
                                    </lightning-button>
                                </footer>
                            </div>
                        </section>

JS:

 handleonClickParentSave() {

const allValid = [
  ...this.template.querySelectorAll("lightning-input")
].reduce((validSoFar, inputCmp) => {
  inputCmp.reportValidity();
  return validSoFar && inputCmp.checkValidity();
}, true);


createParentGuardian({
  firstName: this.firstname,
  lastName: this.lastName,
  phone: this.phone,
  email: this.email,
  studentRelation: this.relationship,
  enrollmentName: this.recordId
})
  .then(result => {
    this.returnResult = result;
    console.log("this.returnResult --> " + this.returnResult);
    if (result) {
      console.log("result1 -->" + this.returnResult);
      this.variant = "success";
      this.title = "Success";
      this.message = "Sucessfully Created";
      this.closeStudentParentModal();
    } else {
      console.log("result1 Else -->" + this.returnResult);
      this.variant = "error";
      this.title = "Error";
      this.message = "Failed to Create";
    }
  })
  .catch(error => {
    this.returnResult = false;
    if (error) {
      console.log("result2 -->" + this.returnResult);
      this.variant = "error";
      this.title = "Error";
      this.message = error;
    }
    console.log("error -->" + error);
  });

}
2
  • I guess you have to set required="true".
    – User6670
    Mar 25, 2020 at 4:25
  • tried that too, LWC1037: To set a boolean attributes, try <lightning-input-field required> instead of <lightning-input-field required="true"> Mar 25, 2020 at 4:27

1 Answer 1

4

You need to understand the required attribute of the lightning-input-field component.

  1. To make an input field required on the server, mark the field Required in Setup. Input fields set as required on the server are universally required, to be displayed with a red asterisk wherever the input fields are used.
  2. To make an input field required on the client only, include the required attribute in lightning-input-field. Use this attribute if you want to require a value in a field before the form can be submitted, and the field isn't marked required in Setup. If the field doesn't have a value, the component's client-side validation catches the error before the form data is submitted to the server.

In your case, you are using custom handler to save the record using onclick event, not the lightning data service one, So what happens is when you click the button, your handleonClickParentSave method gets called first, then lightning data service standard methods gets called to validate the form and submit the form.

What you have to do is:-

For lightning-input-field, if you want to validate your field dynamically on button click, You can do like:-

this.template.querySelector('lightning-input-field').reportValidity();

reportValidity() method validate the field in lightning-input-field.If there is no issue, then only you call your apex method.

Note:- Also as you are using the lightning-record-edit-form, you need to prevent the form to be submitted via its standard functionality as you are overiding it with cutsom apex controller method.

To do so, define onsubmit event and prevent it from submitting to the server.

handleSubmit(event){
   event.preventDefault();       // stop the form from submitting
}

and

<lightning-record-edit-form object-api-name="Contact" onsubmit={handleSubmit}>
</lightning-record-edit-form>

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .