How to get the current field value in Yup when function - yup

How should I get the password field value inside the when to compare the label value with the current value, so that I can strip the field?
*password: string().trim()
.notRequired()
.when(['$config', '$test', 'authenticationMethodType'],
(config: TestConfig, test: SyntheticPropertiesState,
authenticationMethodType: AuthenticationMethodType, schema: StringSchema):
StringSchema => {
const passwordPlaceholderCheck =
test?.authentication?.password !== Localize.PasswordPlaceholder;
if (passwordPlaceholderCheck) {
return schema.label(Localize.Password).required();
}
return schema.strip(true);
})
.max(63)
,*

Related

RTK Query - Delete cache entry if ID is undefined

I have a RTK Query API that fetches a user by ID. This ID is stored in state.
const useUser = () => {
// This can be a string or undefined.
const userID = useTSelector((state) => state.users.userId)
// If the userID above becomes undefined,
// for example if it is set from somewhere else
// then we should clear the result of the below query from the cache.
const {data: user} = useGetUserByIdQuery(userId)
return { user }
}
However, if that ID becomes undefined, I would then like to remove the cached user from the query.
Is this possible out of the box?
You can set skip or use skipToken, which will reset the full hook state and not fire a query.
import { skipToken } from '#reduxjs/toolkit/query/react'
useGetUserByIdQuery(userId == undefined ? skipToken : userId)

Set form value from url parameter

I am using Typo3 10LTS and I would like to set the value of a form field with a parameter value from the URL.
E.g. the value "123" should be entered into the form field "field-1" via the URL www.test-xyz.de/sidename?field-1=123.
Thanks,
Stephan
Fluid
Let's say we have a fluid link, with parameter "123"
<f:link.page pageUid="999" additionalParams="{param: '123'}" noCacheHash="true">Link to Form</f:link.page>
This sends the parameter to the page with the form, containing the value in the URL:
www.test-xyz.de/sitename?param=123
See: link.page Documentation
jQuery
We can now use a few lines of jQuery to populate a field with the value from the URL:
$(".myForm").each(function() {
// Function to sanitize output
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
};
// Populate the input field '.field1' with the parameter in the URL
if (getURLParameter('param') !== null) {
var value = getURLParameter('param');
$('.field1').each(function(){
$(this).val(value);
});
};
});

Only update not null fields to Mongodb from Pojo

I want to update only those fields in mongo document that have values in the POJO. How do I do this?
I have a User collection with the following document:
{
_id: ObjectId("someId"),
name: "Foo",
age: 20,
gender: "male"
}
Now I want to update only the age to 22 so, I have a User pojo with age = 22 and _id = ObjectId("someId").
I don't want to use Updates.set("age",22) because then I'll have to handle every field. The field to be populated may be something other than age.
So, I used reflection to make a generic method to get the list of Update.sets for the pojo
classMembers = User::class.memberProperties
// get hashmap from pojo
val fieldsMap: HashMap<String, Any> =
mapper.convertValue(pojo, object : TypeReference<HashMap<String, Any>>() {}) ?:
throw CustomException( HttpStatus.BAD_REQUEST, "Could not parse request" )
// get hashmap from default/empty pojo
val defaultMap: HashMap<String, Any> =
mapper.convertValue(emptyPojo, object : TypeReference<HashMap<String, Any>>() {}) ?:
throw CustomException( HttpStatus.BAD_REQUEST, "Could not parse request" )
for (member in classMembers) {
val name = member.name
val value = fieldsMap[name]
//add to list only if the current value is not null or default and current value is different
if (value != null && defaultMap[member.name] != value && member.getter.annotations.isNotEmpty()) {
val field = (member.getter.annotations[0] as BsonProperty).value
setList.add(Updates.set(field, value))
}
}
This works. But I wanted to know if theres a better way to do it? A default way to do this via mongoClient or mongoTemplate or mongoRepository?

Axios: How to get data within axios

I created a search for a unique barcode. Therefore the result will be 0 or 1 because it is unique. If barcode is found, I need to get the ID of that record. How do we do this?
axios.get("api/findpatronbarcode?q=" + query)
.then(({data}) => {
this.loanpatrons = data.data;
//COUNT RECORDS
this.countPatrons = this.loanpatrons.length;
console.log(this.countPatrons);
//THE PROBLEM IS THE CODE BELOW. IT RETURNS "Undefined"
// Get the ID of the record
var getID = this.loanpatrons.id;
console.log(getID)
});
You can try like this:
axios.get("api/findpatronbarcode?q=" + query)
.then(({data}) => {
this.loanpatrons = data.data;
//COUNT RECORDS
this.countPatrons = this.loanpatrons.length;
console.log(this.countPatrons);
// KEEP IN MIND THAT "loanpatrons" is Array
// so first get the first member of the Array
// and only then Get the ID of the record
var getID = (this.loanpatrons[0] || {}).id || '';
console.log(getID)
});

specify field name instead of "value"

I have to validate value by value instead of passing in a whole schema for multiple values. Based on the docs for single value validation from here
https://hapi.dev/module/joi/
and this sample code
const validator: AnySchema = Joi.string().valid('foo', 'bar').required();
const validationResult: ValidationResult = validator.validate('invalid');
const validationError: ValidationError = validationResult.error;
if (validationError) {
throw validationError;
}
The code will throw an error with the following error message
ValidationError: "value" must be one of [foo, bar]
Is there an easy way I can replace "value" with a specific name? So when I want to validate environment the error message could be
ValidationError: "environment" must be one of [development, production,
test]
or is that only possible when validating multiple values at once?
There is the any.label(name) method that you can use and set a custom label that will be displayed in error messages as well:
any.label(name)
Overrides the key name in error messages.
name - the name of the key.
const schema = {
first_name: Joi.string().label('First Name')
};
You can simply do:
const validator: AnySchema = Joi
.string()
.label('Foo/Bar') // Change tha label using label method
.valid('foo', 'bar')
.required();
const validationResult: ValidationResult = validator.validate('invalid');
const validationError: ValidationError = validationResult.error;
if (validationError) {
throw validationError;
}
will output:
ValidationError: "Foo/Bar" must be one of [foo, bar]