password check without using regex in reactjs - reactjs

I'm trying to validate the password without using regex
but it didn't work
what I'm trying to do is the password must contain at least one uppercase letter, one lowercase letter, one number, and one alphanumeric character.
but without using Regex
here is my code
import * as React from "react";
import { useForm } from "react-hook-form";
function Form() {
const { register, handleSubmit, errors } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input
type="password"
placeholder="password"
name="password"
ref={register({required:true,minLength:8, maxLength:16, upperCase:'true' , lowerCase:'true' )}
/>
<input type="email" placeholder="email" name="Email" ref={register} />
<br />
Birthday
<input
type="date"
placeholder="birthday"
name="birthday"
ref={register}
/>
<br />
<input type="submit" />
</form>
);
}
export default Form;
I have looked at many sites but I couldn't find any solutions!

Yes, you can simply loop over your string and compare each character (which are numbers represented in the ASCII table). Then you can simply check the counts according to the constraints you want to set.
const password="MyPA55w()rd";
let upper_count = 0;
let lower_count = 0;
let number_count = 0;
let symbol_count = 0
for(let i = 0; i < password.length; i++) {
let c = password.charAt(i);
if( 'A' <= c && c <= 'Z') {
upper_count +=1;
}else if( 'a' <= c && c <= 'z') {
lower_count +=1;
}else if( '0' <= c && c <= '9') {
number_count +=1;
} else {
symbol_count += 1;
}
}
console.log(`Number of capital letter: ${upper_count}`);
console.log(`Number of lower letter: ${lower_count}`);
console.log(`Number of numbers: ${number_count}`);
console.log(`Number of symbols: ${symbol_count}`);
PS: there are also interseting tools like Formik and Yup that allows to you to check return fields in forms.

this one kind of solution is for js vanilla, not for react spezified:
if you don't want to use regex (regex is really nice, you should learn regex) you can create a character map for each charset that you want to check. then iterate through your password and see if the current character is in one of these character maps. additional you can create theese character maps automatically using ascii tables/codes

Related

ReactJS - I implement Binary Search Function, it works only first time

ReactJS - I implement Binary Search Function, it works only first time but after I change the value in the input box, it always return -1 even it has the value in the Array.
Please see the following code:
import React, { useState } from 'react'
import { Container } from 'react-bootstrap'
const binarysearch = () => {
const [ insertValue, setInsertValue ] = useState(0)
var exarr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
// Binary Search
const binarySearch = (arr, val) => {
let start = 0, end = arr.length - 1
while (start <= end) {
let mid = Math.floor((start + end)/2)
console.log(mid)
if (arr[mid] === val) {
return mid
}
if (val < arr[mid]) {
end = mid - 1
} else {
start = mid + 1
}
}
return -1
}
// End Binary Search
return (
<div>
<br />
<hr />
<Container>
<h1>Binary Search</h1>
<h4>Array = {JSON.stringify(exarr)}</h4>
<h4>Search <input type="number" onChange={e => setInsertValue(e.target.value)} /></h4>
<h3>Search {insertValue}, Result in location: {binarySearch(exarr,insertValue)}</h3>
</Container>
<hr />
</div>
)
}
export default binarysearch
First Time Load
After Change Input (Search 10 it should return 10 but -1)
The problem is the fact that e.target.value is always a string, even when the input type attribute is set to "number".
So, when you do arr[mid] === val it will be always false, since this is comparing a number to a string.
You can see this behaviour here.
To fix this, do onChange={e => setInsertValue(Number(e.target.value))}.
Or, alternatively, you can use the non strict equality comparison, which is not really recommended, by replacing the === operator by just ==.
Thank you very much #Mario Vernari
I update the below line to change from string to number, it works properly.
(Insert '+' to insertValue)
From
<h3>Search {insertValue}, Result in location: {binarySearch(exarr,insertValue)}</h3>
To
<h3>Search {insertValue}, Result in location: {binarySearch(exarr, +insertValue)}</h3>

How to prevent a user pasting specific special characters (only allowed characters include (_ - .) in a form using jsx

I also want to limit the first character to just a number or a letter.
This is what I have so far to prevent the user from typing in special characters:
validate(event) {
const keycode = event.keyCode || event.which || event.type === 'paste';
const key = String.fromCharCode(keycode);
const pattern = new RegExp('^[a-zA-Z0-9\\_\\.\\-]$');
return pattern.test(key) ? key : event.preventDefault();
}
const validateMyField = (currentFieldValue, props) => {
if (currentFieldValue.match(/^[a-zA-Z0-9\\_\\.\\-]+$/)) {
return true;
}
return false;
};
const templateNameValidator = createValidator(
validateMyField,
'You are attempting to paste with characters that are not allowed. Please remove characters and try again. (special characters can only include "_","-",".")'
);
<Field
className="usaa-input"
component={Textarea}
label="Template Name"
name="name"
maxLength={128}
minRows={1}
placeholder="Enter Template Name..."
validate={composeValidators(required, templateNameValidator)}
onKeyPress={this.validate}
/>
It might be easier to use a controlled input. This is where we get and set the value to and from the state.
this.state = {inputValue: ""}
...
validateBeforeInput(e){
if(matches the chars we want){
this.setState({inputValue: e.target.value})
}
}
...
<input
value={this.state.inputValue}
onChange{validateBeforeInput} // where the magic happens
/>

chrome.storage.local.get iterate simultaneously through keys and elements

First of all, sorry if the original question isn't clear enough,
I was struggling to define the exact problem I'm having.
I am making a Chrome extension which features a list of blank input boxes. I would like to save the value assigned in those input boxes using the chrome.storage.set method, and retrieve said values into their original input boxes when the popup is reopened.
So far, I have managed to store locally the values of the boxes using a loop, assigning each value a key depending of its order of iteration.
HTML
<input type="text" class="random" value="">
<input type="text" class="random" value="">
<input type="text" class="random" value="">
<button id="4">save</button>
JS
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("4").addEventListener("click", save);
});
function save() {
var id = document.querySelectorAll("input[type='text']");
for (i = 0; i < id.length; i++) {
var inputValue= id[i].value;
if (id.length > 0) {
var key = "key"+i;
chrome.storage.local.set({[key]: inputValue});
alert(key)}
}
}
The problem comes when I try to retrieve each value and return it to its original input field. My solution was to create another loop which iterates through the input fields while retrieving the corresponding keys, but can't seem to make it work.
window.onload = () => {
const id = document.querySelectorAll("input[type='text']");
for (i = 0; i < id.length; i++) {
if (id.length > 0) {
var key = "key"+i;
chrome.storage.local.get([key], (data) => {
if (data.key) {
id[i].value = data.key;
}
});
}
}}
How should I define the variables properly? Is there any other work around to achieve the same result?

in redux-form, how to restrict the values of the input to a range?

I want the user to be able to type numbers up to 2000, and anything beyond 2000 would be simply fed back into the input as '2000'.
<input type="number" className="no-spin"
min="0" max="2000"
value={???}
{...eval(`${meal}_salt_amt_1`)} />
BTW, the 'max' attribute only stops the user from using the up-arrow to increment above 2000.
And redux-form's 'validate' function doesn't restrict what can be typed.
Here is how I'm restricting the value (in state) to 2000...
export function updateStats(values) {
for (var value in values){
if (value.search('salt_amt') >= 0) {
if ( values[value] > 2000) values[value] = 2000;
}
}
return {
type: UPDATE_STATS,
stats: JSON.parse(JSON.stringify(values))
};
}
... so far so good, because in my DevTools redux plugin, I can see the state of these values topping out at 2000.
But how do I force that state back into my redux-form input fields?
Mapping the state to props and using the prop isn't working. Doing so lets me type any number over 2000...
function mapStateToProps(state) {
return {
...
breakfast_salt_amt_1: state.stats.breakfast_salt_amt_1,
...
}
}
<input type="number" className="no-spin"
min="0" max="2000"
value={breakfast_salt_amt_1}
{...breakfast_salt_amt_1} />
And just using the state isn't working either...
<input type="number" className="no-spin"
min="0" max="2000"
value={state.stats.breakfast_salt_amt_1}
{...breakfast_salt_amt_1} />
// => Uncaught TypeError: Cannot read property 'stats' of null
What have I forgotten?
This is what Normalizing is for. Something like this (untested):
const under2k = value => {
if(value < 0) {
return 0
} else if(value > 2000) {
return 2000
} else {
return value
}
}
<Field
name="breakfastSaltAmt"
component="input"
type="number"
normalize={under2k}/>
export const maxLenght = max => value => {
let v;
let result = value.length > max;
if(result === false) {
v = value;
}
return v;
};
<Field
name="name"
type="text"
component={renderField}
label="Nome Completo *"
placeholder="Nome Completo"
normalize={maxLenght(10)}
/>
I think this can help you:
<input type="number" className="no-spin"
min="0" max="2000"
value={this.props.breakfast_salt_amt_1}
{...breakfast_salt_amt_1} />

Apply Range Validation for Input Value AngularJS

When an user entering a value, system should check whether this value is within the range of Minimum and Maximum defined for this field. also, need check for number of decimal points allowed.
<input ng-model='data.value1' >
<input ng-model='data.value2' >
<input ng-model='data.value3' >
<input ng-model='data.value4' >
you can add type="number". and for angularJS
<input type="number"
ng-model=""
[name=""]
[min=""]
[max=""]
[required=""]
[ng-required=""]
[ng-minlength=""]
[ng-maxlength=""]
[pattern=""]
[ng-pattern=""]
[ng-change=""]>
Follow the link for more clarification
AngularJs Documentation
Extending My comment:
var range = 'your range';
var checkRange = function () {
var value = data.value;
if(value <=range) {
//your code;
} else {
//your code;
}
}
Update:
$scope.data.value = 500;
$scope.$watch('data.value', function (oldVal,newVal) {
if(newVal > 1000 ) {
$scope.data.value = 500;
}
})

Resources