I have a function in my angular application in which I have to go through the properties of a form and check which ones have the property "required" = true and then check if the user has already entered this information previously. With this validation I will skip the form if the corresponding user information already exists or I will show the form otherwise.
UPDATE
I've gone so far as to check if they have values through a couple of 'foreach' but I'm stuck at that point and I don't see how to solve what I need to do.
The function is the following
const initForm = getInitForm();
const user = getUser();
const dataNotFilled = [];
initialForm.props.forEach((prop) => {
if (prop.required) {
const nestedObjectData = {};
Object.keys(user).forEach((initKey) => {
const value = user[initKey];
if (initKey === prop.name && value === null) {
dataNotFilled.push(value);
} else if (typeof value === 'object') {
Object.assign(nestedObjectData, value);
Object.keys(nestedObjectData).forEach((key) => {
const nestedValue = nestedObjectData[key];
if (key === prop.name && nestedValue === null) {
dataNotFilled.push(nestedValue);
}
});
}
});
if (dataNotFilled.length) {
browserHistory.push(ADD_USER_DATA_PATH);
}
}
});
and this is the object of the required data of the form that I receive
{
"label": "city",
"name": "city",
"type": "text",
"parent": "primaryAddress",
"validations": [
{
"message": "error",
"value": {
"pattern": "^\\d{2}-\\d{3}$|\\d{5}"
},
"rule": "regex"
},
{
"message": "required",
"value": true,
"rule": "required"
}
],
"required": true,
"services": []
}
and this is the object of the user
{
"name": "John",
"surname": "Martin",
"email": null,
"address": null,
"phone": {
"home": null,
"mobile": null
},
"address": {
"code": "null",
"address": null,
"city": "Kansas"
}
}
How can I compare the properties of both objects to skip the form if the information already exists? thank you all for your time and help in advance.
I think you are making this too complex. Why not simply do something like this:
//Fill the form with your initial object, if any.
this.form = formBuilder.group({
name: [{value: initialObject.name, disabled: initialObject.name !== null}] // Or '' or undefined
surname: [{value: initialObject.surname, disabled: initialObject.surname !== null}]
})
// Other logic.
if(form.valid){
// Form is instantly valid so skip it.
}