how to find and compare separate objects value in array of objects - javascript

I'm trying to make a React registration form.
I have the task to create input fields for form and check their values by regex and comparing values of password and repeat password with email.
It's OK but check values of password and r.password is hard
const fieldsValidation = () => {
const newState = [...fieldsState];
for (let [index, element] of newState.entries()) {
if (element.value.length < element.valueLength) {
return changeFields(() => {
newState[index].error = true;
return newState;
});
}
};
return registerUser();
};
this is configuration which I'm trying to integrate with my react project
export const textFieldConfig = [{
id: 'email',
type: 'email',
label: 'email',
value: '',
variant: 'outlined',
size: 'small',
error: false,
helperText: 'email must include 8 char and #.',
valueLength: 8
},
{
id: 'password',
type: 'password',
label: 'password',
value: '',
variant: 'outlined',
size: 'small',
error: false,
helperText: 'password must be min 6',
valueLength: 6
},
{
id: 'repeatPassword',
type: 'password',
label: 'repeat-password',
value: '',
variant: 'outlined',
size: 'small',
error: false,
helperText: 'please include same password value',
valueLength: 6
}
];

I suppose if your Object are not changing this will do
if(textFieldConfig[1].value == textFieldConfig[2].value){
....
}

Related

ExtJS - Optional model field with validation

In ExtJS 6.02 is it possible to have a field model that is optional but also has validation?
Example an email field that may or not be present but the email must be valid if it exists.
Ext.define('my_model', {
extend : 'Ext.data.Model',
identifier: {
type : 'sequential',
seed : 1,
increment : 1
},
fields: [{
name : 'date',
type : 'date'
}, {
name : 'msg',
type : 'string',
}, {
name : 'email',
type : 'string',
}],
validators: {
date: {
type: 'presence'
},
msg: {
type : 'length',
min : 2
},
email: {
type : 'email'
}
}
});
You can override matcher of email validator to allow empty string:
Ext.define('my_model', {
extend: 'Ext.data.Model',
identifier: {
type: 'sequential',
seed: 1,
increment: 1
},
fields: [{
name: 'date',
type: 'date'
}, {
name: 'msg',
type: 'string',
}, {
name: 'email',
type: 'string',
allowBlank: true
}],
validators: {
date: {
type: 'presence'
},
msg: {
type: 'length',
min: 2
},
email: {
type: 'email',
// Override matcher to allow empty string
matcher: /^$|^(")?(?:[^\."])(?:(?:[\.])?(?:[\w\-!#$%&'*+\/=?\^_`{|}~]))*\1#(\w[\-\w]*\.){1,5}([A-Za-z]){2,6}$/
}
}
});
Ext.application({
name: 'Fiddle',
launch: function () {
var myModel = Ext.create('my_model', {
date: new Date(),
msg: 'Some Message',
//email: 'mustermann#gmail.com',
email: '',
});
console.log(myModel.isValid());
}
});

Objects gets empty in VueJS Component

I'm trying to build an application in VueJS where I'm having a component something like this:
<template>
<div>
<base-subheader title="Members" icon="la-home" heading="Member Details" description="Home"></base-subheader>
<div class="m-content">
<div class="row">
<div class="col-xl-6">
<nits-form-portlet
title="Add Member/User"
info="Fill the details below to add user, fields which are mandatory are label with * (star) mark."
headIcon="flaticon-multimedia"
headerLine
apiUrl="api/user"
backUrl="members__home"
action="create"
:formElements="form_elements"
>
</nits-form-portlet>
</div>
<div class="col-xl-6">
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "member-add",
data() {
return {
form_elements: [
{
field_name: 'first_name',
config_elements: {
label: 'First Name *',
type: 'text',
inputStyle: 'pill',
placeholder: 'Enter first name of user',
formControl: true,
addonType: 'left-icon',
addon: {leftAddon: 'la-exclamation'},
},
value: '',
nitsFormType: 'nits-input'
},
{
field_name: 'last_name',
config_elements: {
label: 'Last Name',
type: 'text',
inputStyle: 'pill',
placeholder: 'Enter last name of user',
formControl: true,
addonType: 'left-icon',
addon: {leftAddon: 'la-exclamation'},
},
value: '',
nitsFormType: 'nits-input'
},
{
field_name: 'email',
config_elements: {
label: 'Email *',
type: 'email',
inputStyle: 'pill',
placeholder: 'Enter email of user',
formControl: true,
addonType: 'left',
addon: {leftAddon: '#'},
},
value: '',
nitsFormType: 'nits-input'
},
{
field_name: 'password',
config_elements: {
label: 'Password *',
type: 'password',
inputStyle: 'pill',
placeholder: 'Enter password',
formControl: true,
addonType: 'left-icon',
addon: {leftAddon: 'la-expeditedssl'},
},
value: '',
nitsFormType: 'nits-input'
},
{
field_name: 'confirm_password',
config_elements: {
label: 'Confirm Password *',
type: 'password',
inputStyle: 'pill',
placeholder: 'Confirm password should match',
formControl: true,
addonType: 'left-icon',
addon: {leftAddon: 'la-expeditedssl'},
},
value: '',
nitsFormType: 'nits-input'
},
{
field_name: 'role',
config_elements: {
label: 'Select Role *',
inputStyle: 'pill',
options: [
{option: 'Select one'},
{value: '1', option: 'Admin'},
{value: '2', option: 'Subscriber'},
{value: '3', option: 'Analyst'},
{value: '4', option: 'Guest'}
],
addonType: 'left-icon',
addon: {leftAddon: 'la-user-secret'},
},
value: '',
nitsFormType: 'nits-select'
},
{
field_name: 'profile_pic',
config_elements: {
label: 'Profile pic',
},
value: '',
nitsFormType: 'nits-file-input'
}
],
}
}
}
</script>
<style scoped>
</style>
Whenever I try to pass data to my component config_elements which holds an object of all attributes being passed to child component gets lost, if I move from other component to nits-form-portlet> it renders the child components appropriately, but in my Vue-debug tool it shows empty:
But the components are rendered properly:
And same happens to the props inside the component:
But in case of any event or refreshing the page it shows:
Since all the attributes are gone, if I try to configure my config_elements object data, I get the attributes but within a fraction of seconds it again goes to empty. But attributes gets passed and it displays the fields:
I am using render function to render these components so for nits-form-portlet component I have:
return createElement('div', { class: this.getClasses() }, [
createElement('div', { class: 'm-portlet__head' }, [
createElement('div', { class: 'm-portlet__head-caption' }, [element])
]),
createElement('form', { class: 'm-form m-form--fit m-form--label-align-right' }, [
createElement('div', { class: 'm-portlet__body' }, [
createElement('div', { class: 'form-group m-form__group m--margin-top-10' }, [infoElement]),
this.computedFormElements.map(a => {
if(this.error[a.field_name]) {
a.config_elements.error = this.error[a.field_name][0];
return createElement(a.nitsFormType, { attrs: a.config_elements, on: {
input: (event) => {
this.form[a.field_name] = event
}
}})
}
else
return createElement(a.nitsFormType, { attrs: a.config_elements, on: {
input: (event) => {
this.form[a.field_name] = event
}
}})
})
]),
footerElement
])
])
And I think factors affecting the template is this map statement:
this.computedFormElements.map(a => {
if(this.error[a.field_name]) {
a.config_elements.error = this.error[a.field_name][0];
return createElement(a.nitsFormType, { attrs: a.config_elements, on: {
input: (event) => {
this.form[a.field_name] = event
}
}})
}
else
return createElement(a.nitsFormType, { attrs: a.config_elements, on: {
input: (event) => {
this.form[a.field_name] = event
}
}})
})
but still I'm sharing my whole code of render function, Link to code # github hoping someone can help me with this strange situation.
It's a bit hard to tell for me without running the code, but I've noticed something that may be related.
I see that you're overwriting the formElements prop here:
a.config_elements.error = this.error[a.field_name][0];
Vue usually gives you a warning that you can't do that, but maybe because it's abstracted through the computed it's not doing so.
If you want to extend the data for use in the child component, then it's best to do copy of the object (preferably a deep copy using computed, which will allow you to have it dynamically updated)
because config_elements is an object, when you add error variable you are likely triggering an observer, that may be clearing the data in the parent.
Anyway, it's just a guess, but something you may want to resolve anyway.

How to access to nested objects keys

I am trying to get the value from a data file with nested objects.
I want to create a label for each entry that i have under the EN object. So I would like to end up having a "mail" label a "quote" label and a "phone" label.
In the label I want to put the content of tabLabel and tabIcon by accessing it.
With Object.Keys() i can see the strings but when I try to console.log them I get undefined.
I did this function but is not working:
function generateLabel() {
const keys = Object.keys(TabFormData.EN);
for (let i = 0; i < keys; i += 1) {
return `
<div class="${ID}_tab-form__headerItemWrap">
<label for="taLabel-here"><i class="tabIcon-here"></i></label>
</div>
`;
}
}
This is the data:
const TabFormData = {
EN: {
mail: [
{
tabLabel: 'Email Our Team',
tabIcon: 'fa fa-envelope',
},
{
label: 'First Name',
type: 'text',
name: 'name',
required: true,
hint: 'Please, provide your Name.',
},
{
label: 'Last Name',
type: 'text',
name: 'surname',
required: true,
hint: 'Please, provide your Last Name.',
},
{
label: 'Email Address',
type: 'email',
name: 'email',
required: true,
hint: 'Please, provide a valid email.',
},
{
label: 'Your Message',
type: 'textarea',
required: true,
name: 'message',
hint: 'Write us a message.',
rows: 20,
cols: 50,
},
{
label: 'About You',
required: true,
select: [
'Home use',
'Business use',
'Freelance, professional',
],
},
],
quote: [
{
tabLabel: 'Request a Quote',
tabIcon: 'fa fa-file-invoice-dollar',
},
{
label: 'First Name',
type: 'text',
name: 'name',
required: true,
hint: 'Please, provide your Name.',
},
{
label: 'Last Name',
type: 'text',
name: 'surname',
required: true,
hint: 'Please, provide your Last Name.',
},
{
label: 'Phone Number',
type: 'number',
name: 'telephone',
required: true,
hint: 'Please, provide a valid number',
},
{
label: 'Email Address',
type: 'email',
name: 'email',
required: false,
hint: 'Please, provide a valid email.',
},
{
label: 'Your Message',
type: 'textarea',
required: false,
name: 'message',
hint: 'Write us a message.',
rows: 20,
cols: 50,
},
{
label: 'About You',
required: true,
select: [
'Home use',
'Business use',
'Freelance, professional',
],
},
],
call: [
{
tabLabel: 'Call Me Back',
tabIcon: 'fa fa-phone',
},
{
label: 'First Name',
type: 'text',
name: 'name',
required: true,
hint: 'Please, provide your Name.',
},
{
label: 'Last Name',
type: 'text',
name: 'surname',
required: true,
hint: 'Please, provide your Last Name.',
},
{
label: 'Phone Number',
type: 'number',
name: 'telephone',
required: true,
hint: 'Please, provide a valid number',
},
{
label: 'About You',
required: true,
select: [
'Home use',
'Business use',
'Freelance, professional',
],
},
],
},
IT: {
},
};
Your problem is in the loop.
for (let i = 0; i < keys; i += 1)
In here you're checking if i is less than an array object, which is not what you want.
You want to compare i against the number of items in the array.
So that would become this:
for (let i = 0; i < keys.length; i += 1)
Your string literal is also wrong, ID in this case is an undefined variable. I assume you want the name of the key. For this issue it should become:
<div class="${keys[i]}_tab-form__headerItemWrap">
Also, once you return from the for loop, it'll automatically break on the first iteration (meaning you'll always get only one item). What you could do is build your whole string first then return it.
That would make your function become:
function generateLabel() {
const keys = Object.keys(TabFormData.EN);
var str = "";
for (let i = 0; i < keys.length; i += 1) {
str +=
`<div class="${keys[i]}_tab-form__headerItemWrap">
<label for="taLabel-here"><i class="tabIcon-here"></i></label>
</div>
`;
}
return str;
}
Here's a Fiddle.
If I understand correctly, you are looking something like this:
let cb = (v) => `<div class="${v[0]}"><label for="${v[1][0]['tabLabel']}"><i class="${v[1][0]['tabIcon']}"></i></label></div>`
Object.entries(TabFormData['EN']).map(cb);
Object.keys() returns the only the keys of the object, however it seems that you want to access the values as well. So, in your case Object.entries() is preferred.
I recommend to read the link below:
https://javascript.info/keys-values-entries
As reported by #Adriani6, you have issues in the loop, but to actually answer your question, here's how to access the nested objects:
function generateLabel() {
const keys = Object.keys(TabFormData.EN);
for (let i = 0; i < keys.length; i += 1) {
let currentTabObject = TabFormData.EN[keys[i]];
console.log(currentTabObject[0].tabLabel);
console.log(currentTabObject[0].tabIcon);
}
}
Assuming you assign TabFormData.EN to a variable called data and the Object.keys result of TabFormData.EN to a variable called keys, you can use:
${keys[i]} to retrieve the name and append it to your div classname,
${data[keys[i]][0].tabLabel} to retrieve the tabLabel property value and append it to your <label> tag, and
${data[keys[i]][0].tabIcon} to retrieve the tabIcon property value and append it to your <i> tag.
You can ignore the <hr> tags, the <button> tag and the rendered <div> tags and just check the object property references in the code snippet below if you want. They are just there for illustrating the code results in the jsFiddle and the code snippet below:
/* JavaScript */
var x = document.getElementById('abc');
var btn = document.getElementById('btn');
function generateLabel() {
const data = TabFormData.EN;
const keys = Object.keys(data);
for (let i = 0; i < keys.length; i += 1) {
x.innerHTML += `
<hr>
<div class="${keys[i]}_tab-form__headerItemWrap">
<label for="${data[keys[i]][0].tabLabel}">
<i class="${data[keys[i]][0].tabIcon}-here">
class of this div is ${keys[i]}_tab-form__headerItemWrap, label for this is ${data[keys[i]][0].tabLabel} and icon is ${data[keys[i]][0].tabIcon}
</i>
</label>
</div>
<hr>`
}
}
btn.addEventListener('click', generateLabel);
const TabFormData = {
EN: {
mail: [
{
tabLabel: 'Email Our Team',
tabIcon: 'fa fa-envelope',
},
{
label: 'First Name',
type: 'text',
name: 'name',
required: true,
hint: 'Please, provide your Name.',
},
{
label: 'Last Name',
type: 'text',
name: 'surname',
required: true,
hint: 'Please, provide your Last Name.',
},
{
label: 'Email Address',
type: 'email',
name: 'email',
required: true,
hint: 'Please, provide a valid email.',
},
{
label: 'Your Message',
type: 'textarea',
required: true,
name: 'message',
hint: 'Write us a message.',
rows: 20,
cols: 50,
},
{
label: 'About You',
required: true,
select: [
'Home use',
'Business use',
'Freelance, professional',
],
},
],
quote: [
{
tabLabel: 'Request a Quote',
tabIcon: 'fa fa-file-invoice-dollar',
},
{
label: 'First Name',
type: 'text',
name: 'name',
required: true,
hint: 'Please, provide your Name.',
},
{
label: 'Last Name',
type: 'text',
name: 'surname',
required: true,
hint: 'Please, provide your Last Name.',
},
{
label: 'Phone Number',
type: 'number',
name: 'telephone',
required: true,
hint: 'Please, provide a valid number',
},
{
label: 'Email Address',
type: 'email',
name: 'email',
required: false,
hint: 'Please, provide a valid email.',
},
{
label: 'Your Message',
type: 'textarea',
required: false,
name: 'message',
hint: 'Write us a message.',
rows: 20,
cols: 50,
},
{
label: 'About You',
required: true,
select: [
'Home use',
'Business use',
'Freelance, professional',
],
},
],
call: [
{
tabLabel: 'Call Me Back',
tabIcon: 'fa fa-phone',
},
{
label: 'First Name',
type: 'text',
name: 'name',
required: true,
hint: 'Please, provide your Name.',
},
{
label: 'Last Name',
type: 'text',
name: 'surname',
required: true,
hint: 'Please, provide your Last Name.',
},
{
label: 'Phone Number',
type: 'number',
name: 'telephone',
required: true,
hint: 'Please, provide a valid number',
},
{
label: 'About You',
required: true,
select: [
'Home use',
'Business use',
'Freelance, professional',
],
},
],
},
IT: {
},
};
/* CSS */
<!-- HTML -->
<button id="btn">
Click Me
</button>
<div id="abc"></div>

Mobx react form confirm password issue

I am using mobx-react-form (https://foxhound87.github.io/mobx-react-form/docs/getting-started-class.html) and I have a password rules validation like so, however the confirm password error comes up as soon as I tap outside of the confirm field regardless of the 2 values being exactly the same:
{
name: 'changePassword',
label: 'Change password',
fields: [
{
name: 'password',
label: t('user:Password'),
rules: 'required|string|min:8',
value: ''
},
{
name: 'password2',
label: t('user:Confirm password'),
rules: 'required|string|same:password',
value: ''
}
]
},
as per the documentation this should work as expected.
Didn't spot the fact that the change password section is nested:
{
name: 'changePassword',
label: 'Change password',
fields: [
{
name: 'password',
label: t('user:Password'),
rules: 'required|string|min:8',
value: ''
},
{
name: 'password2',
label: t('user:Confirm password'),
rules: 'required|string|same:changePassword.password',
value: ''
}
]
},

fileLink is not allowed by schema

I'm trying to use Simple Schema in my current Meteor React project but for some reason I can't get it to work.
This is my schema:
Comments.schema = new SimpleSchema({
city: {
type: String,
label: 'The name of the city.'
},
person: {
type: String,
label: 'The name of the person.'
},
location: {
type: String,
label: 'The name of the location.'
},
title: {
type: String,
label: 'The title of the comment.'
},
content: {
type: String,
label: 'The content of the comment.'
},
fileLink: {
type: String,
regEx: SimpleSchema.RegEx.Url,
label: 'The url of the file.'
},
createdBy: {
type: String,
autoValue: function(){ return this.userId },
label: 'The id of the user.'
}
});
And this is my insert:
createSpark(event){
event.preventDefault();
const city = this.city.value;
const person = this.person.value;
const location = this.location.value;
const title = this.title.value;
const content = this.content.value;
const fileLink = s3Url;
insertComment.call({
city, person, location, title, content, fileLink
}, (error) => {
if (error) {
Bert.alert(error.reason, 'danger');
} else {
target.value = '';
Bert.alert('Comment added!', 'success');
}
});
}
I'm saving the value I get back from amazon in a global variable called s3Url. I am able to console.log this variable without a problem but when I want to write it to the database I am getting a "fileLink is not allowed by schema" error.
Anyone see what I am doing wrong?
Here is my comments.js file:
import faker from 'faker';
import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import { Factory } from 'meteor/dburles:factory';
export const Comments = new Mongo.Collection('comments');
Comments.allow({
insert: () => false,
update: () => false,
remove: () => false,
});
Comments.deny({
insert: () => true,
update: () => true,
remove: () => true,
});
Comments.schema = new SimpleSchema({
city: {
type: String,
label: 'The name of the city.'
},
person: {
type: String,
label: 'The name of the person.'
},
location: {
type: String,
label: 'The name of the location.'
},
title: {
type: String,
label: 'The title of the comment.'
},
content: {
type: String,
label: 'The content of the comment.'
},
fileLink: {
type: String,
regEx: SimpleSchema.RegEx.Url,
label: 'The url of the file.'
},
createdBy: {
type: String,
autoValue: function(){ return this.userId },
label: 'The id of the user.'
}
});
Comments.attachSchema(Comments.schema);
And my methods.js file:
import { Comments } from './comments';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { rateLimit } from '../../modules/rate-limit.js';
export const insertComment = new ValidatedMethod({
name: 'comments.insert',
validate: new SimpleSchema({
city: { type: String },
person: { type: String, optional: true },
location: { type: String, optional: true},
title: { type: String },
content: { type: String },
fileLink: { type: String, regEx: SimpleSchema.RegEx.Url },
createdBy: { type: String, optional: true }
}).validator(),
run(comment) {
Comments.insert(comment);
},
});
rateLimit({
methods: [
insertComment,
],
limit: 5,
timeRange: 1000,
});
While working a bit more on it I noticed some things I was doing wrong.
1. I didn't have the right value for my simple schema set up.
2. Some problems have to do with the fact the url has white spaces in it. What can I do to fix this?
3. The current error I am getting is: "Exception in delivering result of invoking 'comments.insert': ReferenceError: target is not defined."
While working a bit more on it I noticed some things I was doing wrong. 1. I didn't have the right value for my simple schema set up. 2. Some problems have to do with the fact the url has white spaces in it. What can I do to fix this? 3. The current error I am getting is: "Exception in delivering result of invoking 'comments.insert': ReferenceError: target is not defined."
Thanks #Khang

Categories

Resources