yup fields required only if other fields are filled in - formik

I use Yup for my Formik form validation.
I have the following contact form :
const contactForm =
{
title: undefined,
firstName: '',
lastName: props.contact?.name,
contactGroup: {
phone: props.contact?.phone || '',
email: props.contact?.email || '',
},
};
when I fill in the fields I would like the lastName field to go to error only when one of the other fields is filled in.
Here is the validation scheme I use to handle form errors
const schema = yup
.object()
.shape<any>({
firstName: yup.string().max(256, 'max-length'),
lastName: yup.string().when(['email', 'phone', 'firstName'], {
is: (email: any, phone: any, firstName: any) =>
email && phone && firstName,
then: yup.string().required('empty').max(256, 'max-length'),
}),
contactGroup: yup.object().shape<any>(
{
phone: yup.string().when('email', {
is: (email: any) => !email || email === '',
then: yup.string().max(256, 'max-length'),
}),
email: yup
.string()
.nullable(true)
.when('phone', {
is: (phone: any) => !phone || phone === '',
then: yup.string().email('invalid').max(256, 'max-length'),
}),
},
[
['phone', 'email'],
['email', 'phone'],
]
),
})
.required();
I modified the yup in the following way:
lastName: yup.string().when(['email', 'phone', 'firstName'], {
is: (email: any, phone: any, firstName: any) =>
email && phone && firstName,
then: yup.string().required('empty').max(256, 'max-length'),
}),
here I ask if the fields email, phone and firstName are filled in the field lastName is set in error.
It works if I do it only on firstName, but if I add email and phone it doesn't work anymore.
I think it comes from the fact that phone and email are in a contactGroup subobject
Is there a solution for this problem ?
lastName should only go into error when one of the fields phone, email or firstName is filled in.

Related

How to set multiple keys and relations for DataLoader with TypeORM?

OneToOne case
For one JoinColumn key in TypeORM, the #Extensions below can work with loader and loadkey.
But in this case, there are two JoinColumn keys: postId and version. How to set them into #Extensions?
#OneToOne(() => PostVersion, {
lazy: true,
cascade: true,
createForeignKeyConstraints: false,
})
#JoinColumn([
{ name: 'id', referencedColumnName: 'postId' },
{ name: 'version', referencedColumnName: 'version' },
])
#Field(() => PostVersion, {
middleware: [dataloaderFieldMiddleware],
})
// How to set both postId and version keys below?
#Extensions({
loader: (dataloaders: IDataloaders) => dataloaders.currentPostVersion,
loadKey: (post: Post) => post.id,
})
current: Promise<PostVersion>;
ManyToMany case
For many to many relation, one side can set #Extensions with one key. Is it right to set the other relation key on the other side in #Extensions?
#ManyToMany(() => Type)
#JoinTable({
name: 'types_posts',
joinColumn: {
name: 'post_id',
referencedColumnName: 'id',
},
inverseJoinColumn: {
name: 'type_id',
referencedColumnName: 'id',
},
})
#Field(() => [Type], {
middleware: [dataloaderFieldMiddleware],
})
// How to set many to many relations keys with dataloader here?
#Extensions({
loader: (dataloaders: IDataloaders) => dataloaders.typeByPostId,
loadKey: (post: Post) => post.id,
})
postboards: Promise<Type[]>;

How tom send email using Mandrill in React.js App?

I am new to mandrill and am using mandrill to send emails in my React application. Also, I've registered my domain in mandril. I've read the documentation but I can't find it.
You can use this code as reference:
import { useEffect} from 'react'
const Checkout = () => {
useEffect(() => {
const requestOptions: RequestInit | undefined = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
key: 'YOUR_API_KEY',
message: {
text: 'Example text content',
subject: 'example subject',
from_email: 'example#gmail.com',
from_name: 'Example name',
to: [
{
email: 'example#target.com',
name: 'Example target name',
},
],
},
}),
}
fetch('https://mandrillapp.com/api/1.0/messages/send.json', requestOptions).then(
async (response) => {
const res = await response.json()
console.log(res)
}
)
}, [])
return (
<h1>Hello</h1>
)
}
export default Checkout

ignore some fileds when updating data

how can i ignore username / email / phone validation check for current user when updating?
update: i also used class validation but user is null and cant reach the current user id there
updateUserMutator(input: UpdateUserInput! ): User #guard(with: ["api"])
input UpdateUserInput {
name: String! #rules(apply: ["min:1","max:255", "required"])
lastname: String! #rules(apply: ["min:1", "max:255", "required"])
username: String! #rules(apply: ["min:1","max:12", "unique:users,username", "regex:/^[a-zA-Z0-9]+/"])
email: String! #rules(apply: ["email", "unique:users,email", "required"])
phone: String! #rules(apply: ["required", "unique:users,phone", "regex:/[0-9]{10}/"])
}
used class validation:
final class UpdateUserInputValidator extends Validator
{
public function authorize()
{
return true;
}
/**
* Return the validation rules.
*
* #return array<string, array<mixed>>
*/
public function rules(): array
{
// get user from context
$id = auth()->id();
return [
'name' => ['sometimes', 'string', 'between:2,25'],
'lastname' => ['sometimes', 'string', 'between:2,25'],
'username' => [
'sometimes',
Rule::unique('users', 'username')->ignore($id, 'id'),
],
'email' => [
'sometimes',
'string',
'email',
'max:255',
Rule::unique('users', 'email')->ignore($id, 'id'),
],
'phone' => [
'sometimes',
'regex:/[0-9]{10}/',
Rule::unique('users', 'phone')->ignore($id, 'id'),
],
];
}
}
but user is null there.
There are more options available to do so.
You could create a mutation for every field you want to update. This way you ignore the other fields and just update the field in request. (more work)
You can do it with your defined input but you should remove the ! characters which makes the fields required. The updated input might look like:
input UpdateUserInput {
name: String #rules(apply: ["sometimes", "min:1", "max:255"])
lastname: String #rules(apply: ["sometimes", "min:1", "max:255"])
username: String #rules(apply: ["sometimes", "min:1", "max:12", "unique:users,username", "regex:/^[a-zA-Z0-9]+/"])
email: String #rules(apply: ["sometimes", "email", "unique:users,email"])
phone: String #rules(apply: ["sometimes", "unique:users,phone", "regex:/[0-9]{10}/"])
}
With the second approach you just send the fields you want to change.
You forget to update the upper part
input UpdateUserInput #validator {
name: String
lastname: String
username: String
email: String
phone: String
}

store results from method in data form

I am going to preface this with I have NOT done this in a LONG time and my mind is mud. So no picking on me just remind me what I am doing wrong or not remembering.
NOTE: This is VueJS 3 / Tailwind 3 inside a Laravel 9 Jetstream Project
I have a method...
locatorButtonPressed() {
navigator.geolocation.getCurrentPosition(
position => {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
},
error => {
console.log(error.message);
},
)
},
and I have a form data
data() {
return {
form: this.$inertia.form({
name: '',
email: '',
password: '',
password_confirmation: '',
birthdate: '',
user_latitude: '',
user_longitude: '',
user_city: '',
user_region: '',
user_country: '',
location: '',
terms: false,
})
}
}
I want to store position.coords.latitude and position.coords.longitude from the method in the form Data under user_latitude and user_longitude respectfully.
What am I forgetting???
The data properties can be accessed via this.PROPERTY_NAME. For example, to set form.user_latitude, use this.form.user_latitude = newValue.
export default {
methods: {
locatorButtonPressed() {
navigator.geolocation.getCurrentPosition(
position => {
this.form.user_latitude = position.coords.latitude;
this.form.user_longitude = position.coords.longitude;
})
},
}
}
demo

$wpdb->update return 500 error in response - Wordpress Ajax

I am trying to create an update user detail system inside wp-admin, request is getting send properly with all data as I checked inside developers tools (network), but response is getting received 500 in red color
public function edit_employee_data()
{
global $wpdb;
$wpdb->update($wpdb->prefix . 'employee', array(
'name' => $_POST['name'],
'dob' => $_POST['dob'],
'email' => $_POST['email'],
'joining_date' => $_POST['joining_date'],
'address' => $_POST['address'],
'salary_package' => $_POST['salary_package'],
'gender' => $_POST['gender'],
'marital_status' => $_POST['marital_status'],
'department' => $_POST['department'],
'designation' => $_POST['designation']
));
}
add_action('wp_ajax_update_employee', array($this, 'edit_employee_data'));
Javascript used for Ajax call:
<script>
jQuery(document).ready(function($) {
$('form.edit_employee').on('submit', function(e) {
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var dob = $('#dob').val();
var joining_date = $('#joining_date').val();
var address = $('#address').val();
var salary_package = $('#salary_package').val();
var gender = $('#gender').val();
var marital_status = $('#marital_status').val();
var department = $('#department').val();
var designation = $('#designation').val();
var message = $('.message').val();
$.ajax({
url: ajaxurl,
type: "POST",
data: {
action: 'update_employee',
name: name,
email: email,
message: message,
dob: dob,
joining_date: joining_date,
address: address,
salary_package: salary_package,
gender: gender,
marital_status: marital_status,
department: department,
designation: designation,
message: message,
},
success: function(response) {
$(".success_msg").css("display", "block");
},
error: function(data) {
$(".error_msg").css("display", "block");
}
});
});
});
</script>
values are getting send properly with the action name but I don't understand why it's not working.
UPDATE operations need WHERE clauses unless you really intend to update all the rows in the table (unlikely in your example). $wpdb->update() has a third argument giving the WHERE filter, but you omitted it.
Figure out how you identify the row--the employee--you want to update. It might be by employee_id, for example.
Then provide something like this as the third arg.
[employee_id => $_POST[employee_id]]

Resources