Page 1 of 1

Select Field on edit form to validate other field values.

Posted: Tue Mar 07, 2023 12:54 pm
by ricklincs
I have a select Field #item# that has CAB | CAB | LOADED | LOADED | EMPTY | EMPTY | VAN | VAN values.
I have 2 input [text} fields #trailerno# and #cargo#
Before saving the record I would like to validate that if #item# is LOADED OR EMPTY that #trailerno# can not be blank also that if #item# is CAB or VAN #trailerno# must be blank. And also if #item# is LOADED or VAN #cargo# can not be blank.
What would be the best way to achieve this? Thank you.

Re: Select Field on edit form to validate other field values.

Posted: Tue Mar 07, 2023 1:30 pm
by kev1n
Hi,

I asked ChatGPT to generate the code and added the nuBuilder specifict nuBeforeSave() function. Place the code in the form's Custom Code.

Code: Select all

function validateFields() {

	let itemValue = item.value;
	let trailernoValue = trailerno.value;
	let cargoValue = cargo.value;

	if ((itemValue === "LOADED" || itemValue === "EMPTY") && trailernoValue.trim() === "") {
	  alert("Trailerno can not be blank for LOADED or EMPTY itemValue.");
	  return false;
	}

	if ((itemValue === "CAB" || itemValue === "VAN") && trailernoValue.trim() !== "") {
	  alert("Trailerno must be blank for CAB or VAN itemValue.");
	  return false;
	}

	if ((itemValue === "LOADED" || itemValue === "VAN") && cargoValue.trim() === "") {
	  alert("Cargo can not be blank for LOADED or VAN itemValue.");
	  return false;
	}
    
      return true;
}


function nuBeforeSave() {

    return validateFields();

}

This code retrieves the values of the "item", "trailerno", and "cargo" fields, and checks if the conditions for each field are met. If a condition is not met, an alert message is displayed and the function returns, preventing the record from being saved. If all conditions are met, the function proceeds with saving the record (you would need to add the code to save the record). Note that the validation is triggered when the user clicks the "Save Record" button. You can adjust this code to fit your specific use case as needed.

Re: Select Field on edit form to validate other field values.

Posted: Tue Mar 07, 2023 3:01 pm
by ricklincs
Thanks Kevin. I am getting "ncaught ReferenceError: Cannot access 'item' before initialization" and the save button stays red on the edit form.

Re: Select Field on edit form to validate other field values.

Posted: Tue Mar 07, 2023 3:05 pm
by kev1n
Code above updated.

Re: Select Field on edit form to validate other field values.

Posted: Tue Mar 07, 2023 3:37 pm
by kev1n
Updated again