Category Archives: JavaScript

How to test for uniqueness of value in Yup.array?

Imagine you have a form with a dynamic amount of inputs – in my case, it is an array of objects holding “name” and “surname” properties and you need to validate that all objects in this array have unique name property.

Example schema:

const users = yup.array().of(yup.object().shape({
    name:  yup.string(),
    surname: yup.string(),
}))

How can you test for uniqueness? There is no built-in validator, but you can create a custom one easily extending Yup.test.  This validator allows you to add a test function to the validation chain. Tests are run after any object is cast. In order to allow asynchronous custom validations all (or no) tests are run asynchronously. A consequence of this is that test execution order cannot be guaranteed.

All tests must provide a name, an error message and a validation function that must return true when the current value is valid and false or a ValidationError otherwise. To make a test async return a promise that resolves true or false or a ValidationError.

For the message argument you can provide a string which will interpolate certain values if specified using the ${param} syntax. By default, all test messages are passed a path value which is valuable in nested schemas.

The test function is called with the current value.

const users = yup.array().of(yup.object().shape({
    name:  yup.string(),
    surname: yup.string(),
})).test(
    'unique',
        t('step2.validation_errors.duplicate').toString(),
        (value) => {
          if (!value) return true;

          const unique = value.filter((v: any, i: number, a: any) => a.findIndex((t: any) => (t.name === v.name && t.surname === v.surname)) === i);
          return unique.length === value.length;
    }
)

Because the uniqueness check is not related to a particular element of the users object but is a general validation constraint for the whole object, the error message will be populated as “errors.people” property of Formik. That’s why I am checking if the erros.users is a string – if it is a string, I should display a general error above all the user’s fields, but if it is an array of errors – it contains errors for a particular index of the users array.

{typeof errors.users === 'string' && <ErrorMessage
name="users"
component="div"
className="elementor-field-group mt-2 text-sm text-red-600 dark:text-red-500"
/>}

How to use bootstrap icons in React project

There are a few ways to go about it but I found this way to be the easiest and simple. First of all, download the package and add it to your dependencies.

npm i bootstrap-icons --save

Then add this line to your styles.css file at the top of your index.js file

import 'bootstrap-icons/font/bootstrap-icons.css';

Now, whenever you write an HTML with i tag with the bi code like below, you’ll see the icon appear!

<i class="bi bi-house"></i>

For example, go to https://icons.getbootstrap.com/icons/house/ we can see the code to the right that the code snippet is indeed “bi bi-house” for the house icon.

Mask email address for GDPR reasons with JavaScript

This is a simple JavaScript function that will mask your email address following this pattern:

  • If it’s not an email, the input string will be returned without modification.
  • If the first part of the email is shorter than 4 characters, the entire username will be masked (me@example.com => *@e*****e.com)
  • If the domain part of the email is shorter than 4 symbols, the entire domain will be masked
    (username@abc.com => u******e@***.com
  • The TLD part (.com/.net/.org and etc) is never masked
  • If the input string contains multiple emails (for example the whole log message from the server), all email addresses found in the string will be processed.
/**
 * Mask email address with asterisks to comply GDPR
 * john.doe@example.com => j******e@e****e.com
 * @param {string} emailAddress email address
 * @returns {string} masked email address
 */
function maskEmailAddress (emailAddress) {
	function mask(str) {
		var strLen = str.length;
		if (strLen > 4) {
			return str.substr(0, 1) + str.substr(1, strLen - 1).replace(/\w/g, '*') + str.substr(-1,1);
		} 
		return str.replace(/\w/g, '*');
	}
	return emailAddress.replace(/([\w.]+)@([\w.]+)(\.[\w.]+)/g, function (m, p1, p2, p3) {		
		return mask(p1) + '@' + mask(p2) + p3;
	});
	
	return emailAddress;
}

return maskEmailAddress('random string username@example.com test');