Reputation: 796
I'm trying to create error messages for form validation in multiple languages. Unfortunately, the transfer of the "target" parameter to my function does not work. Maybe target is interpreted as a string?!
function formMessages(field, target) {
var messages = {
'de' : {
'valueMissing': 'Bitte füllen Sie dieses Feld aus.',
'typeMismatch': {
'email': 'Bitte geben Sie eine E-Mail ein.',
'url': 'Bitte geben Sie eine URL ein.'
}
}
};
// Don't work!
// return messages.de.target;
// This works! But it is not dynamic!
// return messages.de.typeMismatch.email;
}
if (validity.typeMismatch) {
// Email
if (field.type === 'email') return formMessages(field, 'typeMismatch.email');
}
Upvotes: 0
Views: 50
Reputation: 1347
If you are passing strings as arguments then use [ ] notation and pass 'typeMismatch' , 'email' as two separate arguments.
function formMessages(field, target1, target2) {
var messages = {
'de' : {
'valueMissing': 'Bitte füllen Sie dieses Feld aus.',
'typeMismatch': {
'email': 'Bitte geben Sie eine E-Mail ein.',
'url': 'Bitte geben Sie eine URL ein.'
}
}
};
return messages.de[target1][target2];
}
if (validity.typeMismatch) {
// Email
if (field.type === 'email') return formMessages(field, 'typeMismatch', 'email');
}
Upvotes: 0
Reputation: 5309
try this:
function formMessages(field, target) {
var messages = {
de: {
valueMissing: "Bitte füllen Sie dieses Feld aus.",
typeMismatch: {
email: "Bitte geben Sie eine E-Mail ein.",
url: "Bitte geben Sie eine URL ein."
}
}
};
return target.split(".").reduce((re, v) => re[v], messages.de);
// This works! But it is not dynamic!
// return messages.de.typeMismatch.email;
}
if (validity.typeMismatch) {
// Email
if (field.type === "email") return formMessages(field, "typeMismatch.email");
}
messages.de.target
equalsmessages['de']['target']
,so target
works as string.
If you want target
works as variable,it should be messages.de[target]
.
However,in your case,target
is typeMismatch.email
,so you have to use reduce
to accumulate.
Upvotes: 1
Reputation: 68393
Use bracket notation to access the dynamic property
function formMessages(field)
{
var messages = {
'de' : {
'valueMissing': 'Bitte füllen Sie dieses Feld aus.',
'typeMismatch': {
'email': 'Bitte geben Sie eine E-Mail ein.',
'url': 'Bitte geben Sie eine URL ein.'
}
}
};
return messages.de.typeMismatch[ field.type ]; //pass the field.type itself
}
if (validity.typeMismatch)
{
if ( field.type === 'email') return formMessages(field); //pass the field itself
}
Upvotes: 0