Categories
JavaScript Answers

How to convert the Date.now value to a readable format with JavaScript?

Sometimes, we want to convert the Date.now value to a readable format with JavaScript.

In this article, we’ll look at how to convert the Date.now value to a readable format with JavaScript.

How to convert the Date.now value to a readable format with JavaScript?

To convert the Date.now value to a readable format with JavaScript, we can use the toLocaleString method.

For instance, we write:

const date = new Date(Date.now());
console.log(date.toLocaleDateString());

to call Date.now to return a timestamp.

Then we create a Date instance from the timestamp and assign it to date.

Finally, we call date.toLocaleString to return a localized date string.

Conclusion

To convert the Date.now value to a readable format with JavaScript, we can use the toLocaleString method.

Categories
JavaScript Answers React React Answers

How to validate is either string or array of strings with Yup, React and JavaScript?

Sometimes, we want to validate is either string or array of strings with Yup, React and JavaScript.

In this article, we’ll look at how to validate is either string or array of strings with Yup, React and JavaScript.

How to validate is either string or array of strings with Yup, React and JavaScript?

To validate is either string or array of strings with Yup, React and JavaScript, we can use the mixed and when methods.

For instance, we write:

import React from "react";
import * as yup from "yup";
import { Formik, Form, Field } from "formik";

const validationSchema = yup.object().shape({
  email: yup
    .mixed()
    .when("isArray", {
      is: Array.isArray,
      then: yup.array().of(yup.string()),
      otherwise: yup.string()
    })
    .required()
});

export default function App() {
  return (
    <Formik
      initialValues={{ email: "" }}
      validationSchema={validationSchema}
      onSubmit={(values) => {
        console.log(values);
      }}
    >
      {({ errors, touched }) => (
        <Form>
          <Field name="email" />
          {errors.email && touched.email ? <div>{errors.email}</div> : null}
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  );
}

to add a form with the Formik and Form components.

We set the validationSchema prop to an object returned by object and shape to let us validate the value object.

We set the email property of the schema object to an object returned by mixed and when to add conditional validation.

And we set is to Array.isArray to check if email is an array.

If it’s true, then we validate that is an array of strings by setting then to yup.array().of(yup.string()).

Otherwise, we set the otherwise property to yup.string to validate that email is a string.

Conclusion

To validate is either string or array of strings with Yup, React and JavaScript, we can use the mixed and when methods.

Categories
JavaScript Answers

How to prevent arrow keys from changing values in a number input with JavaScript?

Sometimes, we want to prevent arrow keys from changing values in a number input with JavaScript.

In this article, we’ll look at how to prevent arrow keys from changing values in a number input with JavaScript.

How to prevent arrow keys from changing values in a number input with JavaScript?

To prevent arrow keys from changing values in a number input with JavaScript, we can check if the arrow keys are pressed and call preventDefault is they are.

For instance, we write:

<input type='number'>

to add a number input.

Then we write:

const input = document.querySelector('input')
input.onkeydown = (e) => {
  if (e.which === 38 || e.which === 40) {
    e.preventDefault();
  }
}

to select the input with querySelector.

And we set input.onkeydown with a function that checks if the up and down arrow keys with e.which.

Then we call e.preventDefault to stop the arrow keys from changing the input value.

Conclusion

To prevent arrow keys from changing values in a number input with JavaScript, we can check if the arrow keys are pressed and call preventDefault is they are.

Categories
JavaScript Answers

How to call Lodash assign only if property exists in target object with JavaScript?

Sometimes, we want to call Lodash assign only if property exists in target object with JavaScript.

In this article, we’ll look at how to call Lodash assign only if property exists in target object with JavaScript.

How to call Lodash assign only if property exists in target object with JavaScript?

To call Lodash assign only if property exists in target object with JavaScript, we can use the pick and keys method to return an object that only has the keys in the target object.

For instance, we write:

const options = {
  foo: 1,
  bar: 2
}
const defaults = {
  foo: 2,
  baz: 3
}
const o = _.assign(options, _.pick(defaults, _.keys(options)));
console.log(o)

to call pick with the defaults object and the properties that are only in options to return an object with the properties that are only in options.

Then we call assign with options and the returned object to return a new object with the options properties overridden by the properties in the object returned by pick.

Therefore, o is

{
  bar: 2,
  foo: 2
}

Conclusion

To call Lodash assign only if property exists in target object with JavaScript, we can use the pick and keys method to return an object that only has the keys in the target object.

Categories
JavaScript Answers

How to check if times overlap using moment and JavaScript?

Sometimes, we want to check if times overlap using moment and JavaScript.

In this article, we’ll look at how to check if times overlap using moment and JavaScript.

How to check if times overlap using moment and JavaScript?

To check if times overlap using moment and JavaScript, we can use the moment-range plugin.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/4.0.2/moment-range.js"></script>

to add the moment and moment-range scripts.

Then we write:

window['moment-range'].extendMoment(moment);

const start = new Date(2022, 0, 15);
const end = new Date(2022, 4, 23);
const range = moment.range(start, end);

const a = new Date(2022, 1, 15);
const b = new Date(2021, 1, 15);
console.log(range.contains(a))
console.log(range.contains(b))

to add moment-range with

window['moment-range'].extendMoment(moment)

Then we create a moment-range object with moment.range and 2 dates.

Next, we check if dates a and b are in the range by calling range.contains.

Therefore, the first log is true and the 2nd is false since a is in the range and b isn’t.

Conclusion

To check if times overlap using moment and JavaScript, we can use the moment-range plugin.