React keypress input - reactjs

I'm trying to prevent some characters from being entered, but for some reason the ban does not happen. Where was I wrong?
render () {
return <form>
<input
id="username"
type="text"
placeholder="Username"
value={this.state.value}
onKeyPress={this.pale_username.bind(this)}
/>
</form>
}
and function
pale_username(key) {
if((key.charCode < 48 || key.charCode > 57) //numbers
&& (key.charCode < 65 || key.charCode > 90) // AB
&& (key.charCode < 97 || key.charCode > 122) // ab
&& (key.charCode !== 36) // $
&& (key.charCode !== 38) // &
&& (key.charCode < 40 || key.charCode > 41) // ()
&& (key.charCode < 45 || key.charCode > 46) // -.
&& (key.charCode !== 95) // _
&& (key.charCode !== 127) // del
&& (key.charCode !== 8) // BackSpace
&& (key.charCode !== 46))
return false;
}

I would handle the character 'ban' in an onChange handler. One reason is, what happens if someone copy and pastes something into your input? Preventing the input in a keyboard event handler will not work.
I would try something like this:
handleChange(e) {
// Use whatever regex you need.
const filteredInput = e.target.value.replace(/[abAB$&()-_.*]|\d+/g, '');
this.setState(value: filteredInput)
}
And then use it in your input.
<input
id="username"
type="text"
placeholder="Username"
value={this.state.value}
onChange={this.handleChange.bind(this)}
/>

onKeyDown detects charCode and onKeyPress detects keyCode. Try change it for onKeyDown

Related

How to no allow negative decimal and 0 value to an input type number in React JS

I have a input box which should not allow negative decimal value and 0 trying to do using charcode as shown below
<input type="number" min="1" name="minValue"
className="input-box removeNumberArrow" value={this.state.minValue}
onChange={this.handleMinChange} onKeyPress={this.validateEntredVal}/>
Below method is called when ever a key is pressed
validateEntredVal = (event) => {
let charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode > 31 && (charCode <48 || charCode > 57)) && charCode !== 46) {
evt.preventDefault();
} else {
return true;
}
};
Using the above method it will not allow the characters and negative values. problem it should not allow 0 and decimal as well (means the text box value should always accept value greater than zero)
Please help on the same
min="1" is not working
Add min="0" attribute in min tag.

password check without using regex in 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

How to use onkeypress in Lightning web components?

I have to restrict a input field to accept only numbers. We are not using "lightning-input".
How to use below js function in Lightning web component?
function isNumber(evt) {
var iKeyCode = (evt.which) ? evt.which : evt.keyCode
if (iKeyCode != 46 && iKeyCode > 31 && (iKeyCode < 48 || iKeyCode > 57))
return false;
return true;
}
See below:
.html file
<lightning-card>
<div class="slds-m-around_medium">
<input type="number" onkeypress={handleKeyPress} pattern="[0-9]" class="slds-input" />
</div>
</lightning-card>
.js file
handleKeyPress(event) {
let input_number = event.target.value;
console.log('Number: '+input_number);
}
Results/output
I believe it allows "e" & "k" as valid numbers,
here's what I did
.html file
<input class="numfield" onkeydown={onlyNumericAllowed} type="number" >
.js file
onlyNumericAllowed(event) {
if(event.keyCode === 69){
event.preventDefault();
}
const value = event.target.value;
console.log(event.charCode);
if (value && (!/^[0-9]+$/.test(value) || event.keyCode == 0)) {
this.template.querySelector('.numfield').value = value.replace(/\D/g, '');
}
}

Filter out and lower case all characters using onKeyDown (ev: React.KeyboardEvent<HTMLElement>)

I am using the TagPicker which has the event onKeyDown with signature (ev: React.KeyboardEvent<HTMLElement>) => void
Is there a way I can use this event to only allow lower-case letters and the dash - symbol? Ideally I would like to transform upper-case letters to lower-case automatically.
I have found a solution for this, TagPicker has an inputProps attribute which allows to hook up to the input events. Once I found this out, this task became fairly easy:
<TagPicker onResolveSuggestions={this.onResolveSuggestions}
..
inputProps={{
onBlur: () =>
console.log("onBlur called"),
onFocus: () =>
console.log("onFocus called"),
"aria-label": "Tag Picker",
onKeyPress: (e) =>
{
var charInput = e.charCode;
// no modifier key and no lowercase
if(!e.ctrlKey && !e.metaKey && !e.altKey &&
!(charInput >= 97 && charInput <= 122)) {
//UPPERCASE => lowercase
if((charInput >= 65) && (charInput <= 90)){
charInput=charInput+32;
}
//UNDERSCORE => dash
if((charInput == 95)){
//DASH
charInput=45;
}
if((charInput >= 97 && charInput <= 122) || charInput == 45) {
const start = e.currentTarget.selectionStart;
const end = e.currentTarget.selectionEnd;
const isPrevCharDash = (start > 0 && e.currentTarget.value.charAt(start-1) === "-");
if(!((start == 0 || isPrevCharDash) && charInput == 45)){
e.currentTarget.value = e.currentTarget.value.substring(0, start) + String.fromCharCode(charInput) + e.currentTarget.value.substring(end);
e.currentTarget.setSelectionRange(start+1, start+1);
}
}
e.preventDefault();
}
}
}}
/>
Here is a demo.

Numeric only text box in Angular JS

I want to make textbox numeric only in my Angular JS application.
Here is my code-
script.js
app.directive('numbersonly', function () {
return {
restrict: 'A',
link: function (scope, elm, attrs, ctrl) {
elm.on('keydown', function (event) {
if (event.which == 64 || event.which == 16) {
// to allow numbers
return false;
} else if (event.which >= 48 && event.which <= 57) {
// to allow numbers
return true;
} else if (event.which >= 96 && event.which <= 105) {
// to allow numpad number
return true;
} else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) {
// to allow backspace, enter, escape, arrows
return true;
} else {
event.preventDefault();
// to stop others
return false;
}
});
}
}
});
And on UI-
<input type="text" id="txtEmpAge" data-ng-model="newemployee.Age" class="form-control" numbersonly required />
But the text box is accepting both numeric and character.
If it is not necessary to use your own implementation, try Angular's number type input.
You can use type=number
<input type="number" id="txtEmpAge" data-ng-model="newemployee.Age" class="form-control" required />
This will take only number values in the text box.
in my opinion, best way to achieve
, it will also not allow user to copy paste strings to input
<input type="number" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
Use the following snippet to make the input field to accept only characters between 0 to 9. This will eliminate the decimal pointer.
<input type="number" onkeypress="return isNumKey(event)"/>
use this function to trigger on key is pressed.
function isNumKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}

Resources