How to set Password Validation in react - reactjs

How to validate a password like atleast one Capital letter one special character one number and minlength 8 in react Js without use any react library

try
const valid = value.length >= 8 && /[A-Z]/.test(value) && /[^a-zA-Z]/.test(value) && /[0-9]/.test(value)

const passwordRegExp = new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&\.\+\*\{\]\{\[\-,;`<>':"=^#_|\/\\])(?=.*?[A-Za-z\d#$!%*+?&\.\+\*\{\]\{\[\-,;`<>':"=^#_|\/\\]).{8,}/)
const formValueFalse = 'aaabbb'
const formValueTrue = 'AaBb123$'
passwordRegExp.test(formValueFalse)
passwordRegExp.test(formValueTrue)

Related

MUI TextField format input to show numbers and decimals

I'm trying to format the value of the input of this MUI component to show a maximum of 3 numbers following with a maximum of 2 decimals separated by a dot, e.g. 233.99, I want to store this value in a react state called value (const [value, setValue] = useState(0)).
I'm having trouble since I see a lot of approachs to achieve this, but I find it complicated to also keep track if the user already entered the first 3 numbers and not let him enter more while also keeping tack of the decimal values too, since as I said, there should be a maximum of 2 decimals.
I tried regex functions, toFixed js function, and more, but I can't make this work smoothly.
If I understood this correctly, you can achieve this with:
let inp = document.getElementById("input");
inp.addEventListener("keypress", ev => {
ev.preventDefault();
if (!/\d|\./.test(ev.key)) return;
inp.value = /^\d{0,3}(\.\d{0,2})?$/.test(inp.value + ev.key) ? inp.value + ev.key : inp.value;
// update state when value has changed
// if (inp.value != value) setValue(inp.value);
})
<input type="text" id="input">
Alternatively, you can use <input type="text" pattern="^\d{0,3}(\.\d{0,2})?$"> and input.checkValidity() to notify the user on submit.

Emojis become question marks after re-render in contentEditable

I've created a simple text editor and I've also created the possibility to add emojis. The problem is that when I click an emoji the emoji is added and visible, but the previous existing emojis are replaced with question marks. My contentEditable div is controlled, meaning that whenever an emoji is added it causes a re-render. I got this problem in the following if case of my algorithm:
childValue = childValue.substring(0, caretPosition) + emoji + childValue.substring(caretPosition + 1, childValue.length)
childValue isn't a state variable, it's value is used to update a constant variable that will be used to update the state variable representing the contentEditable's dangerouslySetInnerHTML property, the caretPosition is perfect.
Any ideas why I might have this issue?
This solution from https://stackoverflow.com/a/59793087/14550434 combined with HTML escaping should do the trick:
var p = document.querySelector("p");
var childValue = "Some sample text";
var caretPosition = 5;
var emoji = "😀";
const emojiToString = (emoji) =>
` &#x${emoji.codePointAt(0).toString(16)}; `;
childValue =
childValue.substring(0, caretPosition) + emojiToString(emoji) +
childValue.substring(caretPosition, childValue.length);
p.innerHTML = childValue;
<p></p>
I solved this issue. I figured out that 'substring' was messing everything up, so I did the following:
newChildValue = Array.from(childValue);
childValue = newChildValue.slice(0, caretPosition).join('') + emoji + newChildValue.slice(caretPosition).join('');
This way I avoid using 'substring' as Array.from(str) splits a string into individual unicode characters without breaking them between bytes.

React form validation for multiple field

I am new to React. I have a very simple form which contains employer address details. I would like to validate if any of the fields got value, then check if length is <=10 and if not exists the it is fine. There are no mandatory validation and only length valiation if exists.
currently doing like below:
const isValid=
employer.address == null ||
(employer.address != null &&
(employer.address.building?.length <= 2) &&
employer.address.street?.length <= 2 &&
employer.address.county?.length <= 2 &&
employer.address.city?.length <= 2 &&
employer.address.postcode?.length <= 2);
Is there a better way to test to check validation if it contains value and ignore if not.
it is neither bad nor the best way
with current code you can do a bit clean Up to make it look nicer
you can assign a const to employer.address so no need to repeat it
const emp = employer.address
const isValid=
!emp||
(emp&&
(emp.building?) &&
emp.street?&&
emp.county?&&
emp.city? &&
emp.postcode?);
in the example above validation works if data is '' but if it has anything inside it ('s') validation would not be called
i think it should work same way
also there are some packages that provide you validation
redux form
https://redux-form.com/8.3.0/
yup
https://www.npmjs.com/package/yup

How to check if the value of the span element is equal to another value using react testing library?

i want to test if the value of span element is equal to another constant.
What i am trying to do?
I have a span element like below
render = () => {
const compare_value = 5
const span_value = 5
return (
<span data-test-id="test">{span_value}</span>
);
}
Now within my test i do this
const span_element = getByTestId('test');
const value = span_element.innerHTML //this value is "5" a string
expect(value).toBe(compare_value);
Here in the expect statement i get error object.isequality
I get this error since value is string "5" and compare value is integer 5.
How can i fix this. could someone help me with this. I want to test if the value of spanelement is equal to the compare_value.
Thanks.
Cast one of the values ( value or compare_value) to string.
String(compare_value)
//or
compare_value.toString()

Using .Filter When the Filter Criteria are in Pre-existing String (TypeScript/Node.js)

I'm trying to process an array of JSON objects that have various common attributes, filtering each array entry on one or more of those attributes.
Normally, I'd just do it something like this:
let filteredResultsArray = originalArray.filter((obj) => {
return obj.attribute1 <= 3 && obj.attribute2 > 0 && obj.attribute3 === 10;
});
My problem is that the filter parameters (the part after "return" in the code above) are highly variable (and unpredictable) from run to run, so I can't hard-code them in the filter. I compute them on the fly and store the whole thing in a string in my code. For example, on one run it might be:
myAttributeString = "obj.attribute1 <= 3 && obj.attribute2 > 0 && obj.attribute3 === 10";
I've tried doing this:
let filteredResultsArray = originalArray.filter((obj) => {
return myAttributeString;
});
That's failing to filter anything. Apparently .filter() is not properly interpreting what I've stored in myAttributeString as filter criteria.
I have a sneaking suspicion that eval(myAttributeString) might be one way to pull this off, but unfortunately I'm working on a team where we've got tslint set to disallow the use of eval(), so that's not an option.
Anybody have an idea how I can get this to work?
When you "compute them on the fly", instead of creating a string, create a callback function that you can then pass to filter. For example, instead of
const myAttributeString = "obj.attribute1 <= 3 && obj.attribute2 > 0 && obj.attribute3 === 10";
do
const filterCallback = obj => obj.attribute1 <= 3 && obj.attribute2 > 0 && obj.attribute3 === 10
Then, later, when the appropriate time comes to .filter, simply pass that as the callback:
const filteredResultsArray = originalArray.filter(filterCallback);
If you can't pass functions around, another option would be to build an array of conditions, for example
[
{
prop: "attribute1",
constraint: "<=",
value: 3
},
{
prop: "attribute2",
constraint: ">",
value: 0
},
// ...
]
and then turn the object into the filter function needed.
****************************************UPDATE******************************
As I suspected, eval() did work, but since I can't use it in my delivered code, and thanks to CertainPerformance's suggestion (which put my thinking on the right track) as well as the Node.js documentation site (via a lucky Google search), I was able to find a workaround using the vm module:
import * as vm from "vm";
let filteredResultsArray = originalArray.filter(
vm.runInThisContext("(obj) => {
return " + myAttributeString + ";}"));
Case closed.

Resources