cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

Unable to prevent update behaviour while validating input fields ui5

Amit_Joshi1
Explorer
0 Likes
705

this is edit xml fragment 

```

<core:FragmentDefinition
    xmlns="sap.m"
    xmlns:core="sap.ui.core">
    <Dialog id="editDialog" title="Edit Vendor" afterClose=".onDialogClose">
        <VBox>
            <Label text="Full Name" />
            <Input id="inputVendorName" value="{vendorListModel>/vendors/0/fullName}" change=".onFullNameChange" />

            <Label text="Email" />
            <Input id="inputVendorEmail" value="{vendorListModel>/vendors/0/email}" change=".onEmailChange" />

            <Label text="Phone Number" />
            <Input id="inputPhoneNumber" value="{vendorListModel>/vendors/0/phoneNumber}" change=".onPhoneChange" />

            <Label text="Date of Birth" />
            <DatePicker id="inputVendorDob" value="{vendorListModel>/vendors/0/dob}" change=".onDobChange" />
        </VBox>
        <beginButton>
            <Button text="Save" press=".onSavePress" />
        </beginButton>
        <endButton>
            <Button text="Cancel" press=".onCancelPress" />
        </endButton>
    </Dialog>
</core:FragmentDefinition>

```

 I have a controller where I am trying to update values after clicking the edit button. The validation is working and showing an error, but when I provide incorrect input, it still gets updated in the UI after clicking the save button. For example, if I have the email "temp@gmail.com" and I click on edit, then enter "temp" only, it shows a validation error as expected. However, if I click the save button, it updates the UI table with the incorrect value. I want to prevent that from happening.

here is my controller looks,

```

// Triggered when edit button is pressed
     onEditPress: function (oEvent) {
        const oView = this.getView();
        const oContext = oEvent.getSource().getBindingContext("vendorListModel");

        if (!this._oEditDialog) {
            Fragment.load({
                name: "vendornamespace.productionplanning.view.EditVendorDialog",
                controller: this
            }).then((oDialog) => {
                this._oEditDialog = oDialog;
                oView.addDependent(this._oEditDialog);
                this._bindDialog(oContext);
                this._oEditDialog.open();
            });
        } else {
            this._bindDialog(oContext);
            this._oEditDialog.open();
        }
    },

    _bindDialog: function (oContext) {
        this._oEditDialog.bindElement({
            path: oContext.getPath(),
            model: "vendorListModel"
        });
    },
     
    _validateInputs: function () {
        const oDialog = this._oEditDialog;
        const aContent = oDialog.getContent()[0].getItems();
        const oFullNameInput = aContent[1];
        const oEmailInput = aContent[3];
        const oPhoneInput = aContent[5];
        const oDobInput = aContent[7];
   
        let bValidationError = false;
   
        // Validate Full Name
        if (!oFullNameInput.getValue()) {
            oFullNameInput.setValueState("Error");
            MessageToast.show("Full name is required.");
            bValidationError = true;
        } else {
            oFullNameInput.setValueState("None");
        }
   
        // Validate Email
        const sEmail = oEmailInput.getValue();
        const oEmailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        console.log("Email being validated: ", sEmail); // Log email validation attempt
       
        if (!sEmail) {
            oEmailInput.setValueState("Error");
            MessageToast.show("Email is required.");
            bValidationError = true;
        } else if (!oEmailRegex.test(sEmail)) {
            oEmailInput.setValueState("Error");
            MessageToast.show("Invalid email format.");
            bValidationError = true;
        } else {
            oEmailInput.setValueState("None");
        }
   
        // Validate Phone Number
        const sPhoneNumber = oPhoneInput.getValue();
        const oPhoneRegex = /^[0-9]+$/;
        if (!sPhoneNumber) {
            oPhoneInput.setValueState("Error");
            MessageToast.show("Phone number is required.");
            bValidationError = true;
        } else if (!oPhoneRegex.test(sPhoneNumber)) {
            oPhoneInput.setValueState("Error");
            MessageToast.show("Phone number must contain only digits.");
            bValidationError = true;
        } else {
            oPhoneInput.setValueState("None");
        }
   
        console.log("Validation Result: ", !bValidationError); // Log validation result
        return !bValidationError; // Returns true if no validation errors
    },
   
   
 
    onSavePress: function () {
        console.log("Start onSavePress");
   
        // Validate inputs
        const isValid = this._validateInputs();
        console.log("Is Valid Before Update: ", isValid);
   
        // Check validation status and exit if not valid
        if (!isValid) {
            console.log("Validation failed. No updates will occur.");
            MessageToast.show("Please correct the errors before saving.");
            return; // Make sure to exit early
        }
   
        // Proceed with updates since validation has passed
        console.log("Validation passed. Proceeding with update...");
   
        // Access vendor data and proceed to update
        const oVendorData = this._oEditDialog.getBindingContext("vendorListModel").getObject();
        const oModel = this.getView().getModel("vendorListModel");
   
        // Accessing dialog content items
        const aContent = this._oEditDialog.getContent()[0].getItems();
        console.log("Updating vendor data with:", {
            fullName: aContent[1].getValue(),
            email: aContent[3].getValue(),
            phoneNumber: aContent[5].getValue(),
            dob: aContent[7].getDateValue()
        });
   
        // Update properties in the model
        const vendorPath = this._oEditDialog.getBindingContext("vendorListModel").getPath();
        oModel.setProperty(`${vendorPath}/fullName`, aContent[1].getValue());
        oModel.setProperty(`${vendorPath}/email`, aContent[3].getValue());
        oModel.setProperty(`${vendorPath}/phoneNumber`, aContent[5].getValue());
        oModel.setProperty(`${vendorPath}/dob`, aContent[7].getDateValue());
   
        // Close the dialog and show success message
        this._oEditDialog.close();
        MessageToast.show("Vendor details updated successfully.");
    },
   
   
   

    onCancelPress: function () {
        this._oEditDialog.close();
    },

    onDialogClose: function () {
        if (this._oEditDialog) {
            this._oEditDialog.destroy(); // Optional cleanup
            this._oEditDialog = undefined; // Reset the dialog reference
        }
    },

```

@gregorw sir please help me to resolve the bug.

SAP Fiori #  

Accepted Solutions (0)

Answers (0)