update object properties from inside function - javascript

I'm trying to update the values in validations inside of the function it sets isValid to false however it doesn't update validations outside of the function, how can i do this?
export let validations = {
validate: null,
isValid: true,
validationMessage: ''
};
function validateInput(value) {
if (value == null || value.length === 0) {
const update = {...validations, isValid: false}
{console.log(bla)}
return update
}

Have you tried:
export let validations = {
validate: null,
isValid: true,
validationMessage: ''
};
function validateInput(value) {
if (value == null || value.length === 0) {
validations.isValid = false
}
}

Is it that you want the actual validations object to be intact and your validateInput function should return it's validation result
export let validations = {
validate: null,
isValid: true,
validationMessage: ''
};
function validateInput(value) {
const update = {...validations};
if (value == null || value.length === 0) {
update.isValid = false;
}
return update;
}
or something like
export let validations = {
validate: function(value){
if (value == null || value.length === 0) {
this.isValid = false;
this.validationMessage = 'No value'
}},
reset: function(){
this.isValid = true;
this.validationMessage = '';
},
isValid: true,
validationMessage: ''
};

Related

Finding if any key value is true

Hi there I am trying to find out if any key value is true of an object.
The following works only for objects without having nested objects.
I am trying to check if any key in the objects no matter parent or child has got true value
const odb = {
"all": true,
"allA": false,
"allB": false,
"allC": {
"allD": false,
"allE": false,
}
}
const isAnyKeyValueTrue = o => !Object.keys(o).find(k => !o[k]);
console.log(isAnyKeyValueTrue(odb));
Check if the value is an object, and if it is, call isAnyKeyValueTrue again. Also, to be more semantically correct, I have used some instead of find. I use && o[k] to make sure null is not given to the function (since typeof null === "object").
const odb = {
"all": false,
"allA": false,
"allB": false,
"allC": {
"allD": false,
"allE": { "allF": true },
}
}
const isAnyKeyValueTrue = o => Object.keys(o).some(k => typeof o[k] === "object" && o[k] ? isAnyKeyValueTrue(o[k]) : o[k] === true);
console.log(isAnyKeyValueTrue(odb));
The key point is that if we do not find matched result in current level,then we need to use || to find in the children level by invoke the current function recursively
const odb = {
"all": false,
"allA": false,
"allB": false,
"allC": {
"allD": false,
"allE": false,
'allF':{
'allG':true
}
}
}
const isAnyKeyValueTrue = o => Object.values(o).some(v => ((typeof v == `boolean`) && v) || isAnyKeyValueTrue(v))
console.log(isAnyKeyValueTrue(odb));
const odb = {
"all": false,
"allA": false,
"allB": false,
"allC": {
"allD": false,
"allE": { "allF": true },
}
}
const isTrue = (obj) => {
let result = false;
for (let key in obj) {
if (obj[key] === true) {
result = true;
break;
} else if (typeof obj[key] === 'object') {
result = isTrue(obj[key]);
}
}
return result;
}
console.log(isTrue(odb));

LIVR Validate if element in object is empty array

I have LIVR in a project i'm working now and is quite unclear to me how this work. I can't understand how to create new rules for custom validation.
Here's the code:
LIVR.Validator.defaultAutoTrim(true);
let validator = new LIVR.Validator({});
LIVR.Validator.registerDefaultRules({
nested_object_value() {
return function (value) {
if (!value || (value && !value.value || value === [])) {
return 'REQUIRED';
}
return '';
};
},
max_number_advancement() {
return function (value) {
if (value > 100) {
return 'MAX_NUMBER';
}
return '';
};
},
required_if_activity_present() {
return function (value, allValue) {
if (allValue.activitycycletype && !value || allValue.requestpeople === []) {
console.log(first)
return 'REQUIRED_IF_CYCLETYPE';
}
return '';
};
},
});
And this is how its used:
validationForm = () => {
const { formValue, updateErrors } = this.props;
const validData = validator.validate(formValue);
console.log(formValue)
if (!validData) {
const errorsValidator = validator.getErrors();
if (errorsValidator && Object.keys(errorsValidator).length > 0) {
const newErrors = {};
Object.keys(errorsValidator).forEach((error) => {
newErrors[error] = errorsValidator[error];
});
updateErrors(newErrors);
}
blame(t('validation-error'));
return false;
}
updateErrors({});
return true;
}
Opening the form with this validation in the app, seems to call only the last method required_if_activity_present().
What i expect here is that i can create a new method inside registerDefaultRules(), that is a LIVR method, like this:
LIVR.Validator.registerDefaultRules({
re quired_not_empty() {
return function (value) {
if (!value) {
return 'REQUIRED';
}
return '';
};
},
... //other methods
}
but seems not working, the newer method is not being called at all by validator.validate()
Anyone know how to create a new rules where i can check if an element inside the object that has to be validate is an empty array?
Because seems that LIVR doesn't return a validation error in this case, but only on empty string and null values.
Thanks in advance

Block input type radio in React

everyone. I have a problem that arises after changing excluding params. I use Redux to save all params data but I have an incomprehensible error. I add a video that shows that problem. Also, I attach some code parts. All elements are memo. Events are disabled after second param change. video
if (value === "true" || value === "false") {
newValue = value === "true" ? true : false;
}
if (newValue === true && (name === "DU_DT" || name === "SINF")) {
if (name === "DU_DT") {
result = { ...values, DU_DT: true, SINF: false };
} else {
result = { ...values, DU_DT: false, SINF: true };
}
} else {
result = { ...values, [name]: newValue }
}
dispatch({
type: ConfigurationActions.SET_VALUES,
payload: result,
});

Error: Syntax error, unrecognized expression: unsupported pseudo: invalid / ReactJS / Unit Testing

when I make this test, I got the following error: "Error: Syntax error, unrecognized expression: unsupported pseudo: invalid".
I don't know what is the problem on my code. Can someone show me ? Thank you !
jest.disableAutomock();
jest.unmock('../resources/assets/js/testcomponents/InputText.js');
jest.dontMock('react-bootstrap');
_ = require('lodash');
$ = require('jquery');
var React = require('react'),
InputText = require('../resources/assets/js/testcomponents/InputText.js').InputTextEditable,
TestUtils = require('react-addons-test-utils'),
ReactDOM = require('react-dom');
describe('InputText', function () {
var InputElement = TestUtils.renderIntoDocument(
<InputText
area={false}
//evts={{onChange: handleChange}}
attributes={{
label:'Test Input Isole',
name:'InputTextArea',
value: '',
wrapperClassName: 'col-md-4',
labelClassName: 'col-md-2',
groupClassName: 'row'
}}
//ref="InputField"
editable={true}/>);
var DomElement = ReactDOM.findDOMNode(InputElement);
//var inputV = ReactDOM.findDOMNode(InputElement.refs.InputField);
var input = DomElement.getElementsByTagName('input')[0];
it('updates input value on key press', function () {
TestUtils.Simulate.change(
DomElement.getElementsByTagName('input')[0],
{target: {value: 'a'}}
);
expect(input.getAttribute('value')).toEqual('a');
});
EDIT : This is my component
var InputText = React.createClass({
mixins: [MixinInputValue],
propTypes: {
attributes: React.PropTypes.object,
evts: React.PropTypes.object,
gestMod: React.PropTypes.bool,
area: React.PropTypes.bool,
validator: React.PropTypes.func
},
getDefaultProps: function () {
return {
attributes: {},
evts: {},
gestMod: true,
area: false,
validator: function (val, props, state) {
if (val.length == 0 && typeof(props.attributes.required) != 'undefined' && props.attributes.required) {
return {isValid: false, style: 'default', tooltip: ''};
}
else if (val.length == 0) {
return {isValid: true, style: 'default', tooltip: ''};
}
else {
return {isValid: true, style: 'success', tooltip: ''};
}
}
};
},
render: function () {
console.log('passerender');
var attrs = this.generateAttributes();
var type = this.props.area ? "textarea" : "text";
return (
<Input
className={this.props.menuClassName}
type={type}
{...attrs}
{...this.props.evts}
className={this.props.menuClassName}
onChange = {this.handleChange}
onBlur = {this.handleBlur}
value={this.state.value}
ref = "InputField"
hasFeedback
/>
);
}
});
2ND EDIT=
Ok I guess the issue came from this file
getStateAttributes: function (val, DOM) {
var attrs = {};
attrs = _.extend((this.props.gestMod ? {'data-gest-mod': this.props.gestMod} : {}), attrs);
var validation = this.props.validator(val, this.props, this.state, DOM);
var html5Validity = true;
if (DOM !== undefined) {
console.log("petit message", DOM.outerHTML);
var temp = $(DOM.outerHTML);
temp.find('div');
html5Validity = DOM.querySelectorAll(':invalid').length == 0;
// html5Validity = temp.find(':invalid').length == 0;
}
attrs = _.extend({'data-valid': validation.isValid && html5Validity}, attrs);
// 4. AJOUT DU STYLE REACTB
var style = {'bsStyle': (!Validator.matches(validation.style, 'success|warning|error', 'i') ? undefined : validation.style)};
if (!html5Validity) {
style = {'bsStyle': 'error'};
}
if (validation.tooltip.length > 0) {
style.help = validation.tooltip;
}
attrs = _.extend(style, attrs);
return attrs;
},
This code was the problem:
var html5Validity = true;
if (DOM !== undefined) {
console.log("petit message", DOM.outerHTML);
var temp = $(DOM.outerHTML);
temp.find('div');
html5Validity = DOM.querySelectorAll(':invalid').length == 0;
// html5Validity = temp.find(':invalid').length == 0;
}
attrs = _.extend({'data-valid': validation.isValid && html5Validity}, attrs);
I put a try/catch on this to solve my problem and its work ! :
var html5Validity = true;
if (DOM !== undefined) {
try {
html5Validity = $(DOM).find(':invalid').length == 0;
console.log('pass');
} catch (e) {
console.log('catch');
html5Validity = true;
}
}
attrs = _.extend({'data-valid': validation.isValid && html5Validity}, attrs);

How to check if boolean is true in custom validation simple-schema in Meteor

I have the following Schema:
Games.attachSchema(new SimpleSchema({
title: {
type: String,
label: "Title",
max: 30
},
multiplayer: {
type: Boolean,
label: "Multiplayer",
denyUpdate: true
},
description: {
type: String,
label: "Description",
custom: function() {
var multiplayer = this.field("multiplayer");
if (multiplayer.isSet && multiplayer.value && !this.isSet) return "Description is empty!";
return true;
}
}
}));
My goal is to check if description is empty, but only if the checkbox multiplayer has been checked. If the checkbox has not been checked, the description should not be mandatory to fill in.
I tried the code above, but it does not validate. Even if I do not have an description and I checked the checkbox, I am able to submit the form.
I found the proper documentation and I solved it like this:
{
description: {
type: String,
optional: true,
custom: function () {
var shouldBeRequired = this.field('multiplayer').value;
if (shouldBeRequired) {
// inserts
if (!this.operator) {
if (!this.isSet || this.value === null || this.value === "") return "required";
}
// updates
else if (this.isSet) {
if (this.operator === "$set" && this.value === null || this.value === "") return "required";
if (this.operator === "$unset") return "required";
if (this.operator === "$rename") return "required";
}
}
}
}
}
I think the problem is with your validation logic. Try changing it to :
if (multiplayer.isSet && multiplayer.value && this.isSet && this.value == "")
return "Description is empty!";

Categories