React js input onChange Validation is not Working - javascript

onChange={(e) => {
if (e.target.value.match("^[a-zA-Z]*$") != null) {
setName(e.target.value);
// console.log(setName);
} else {
toast.error("Please match the required format");
}
}}
this required validation is not working. database is updated with empty string

You can also use test like:
onChange={(e) => {
if (/^[a-zA-Z]*$/.test(e.target.value)) {
setName(e.target.value);
// console.log(setName);
} else {
toast.error("Please match the required format");
}
}}
Hope it maybe helpful.

onChange = {(e) => {
if(e.target.value.match("^[a-zA-Z]*$") === true){
setName(e.target.value)
} else {
toast.error("Please match the required format")
}
}}

Related

how can you show a "no result found" after filtering?

how can you show a "no result found" after filtering?
const searchItems = (searchValue) => {
setSearchInput(searchValue)
if (searchInput !== '') {
const filteredData = APIData.filter((post) => {
return Object.values(post).join('').toLowerCase().includes(searchInput.toLowerCase())
})
setFilteredResults(filteredData)
}
else{
setFilteredResults(APIData)
}
}
I returned the filtered data but I didn't know how to return a "no result found" if the user types wrong data!
This is the text Input
<OutlinedInput
className="SearchInput"
placeholder='Search...'
onChange={(e) => searchItems(e.target.value)}
endAdornment={
<InputAdornment>
<SearchIcon />
</InputAdornment>
}
/>
I'm using
{searchInput.length > 0 ? () : ()}
You should check your filteredData after you recive the data.
if (searchInput !== '') {
const filteredData = APIData.filter((post) => {
return Object.values(post).join('').toLowerCase().includes(searchInput.toLowerCase())
})
if(filteredData){
setFilteredResults(filteredData);
}else{
console.log("no result found");
}
}
else{
setFilteredResults(APIData)
}
Or check if your response contains some type you are looking for like
if (!isNumber(filteredData.id) && filteredData.id === 0) {
console.log("no result found");
}
You can find some examples over here https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

React.js: How to submit form if inputs are validated?

I have a basic form with two inputs: email and confirmEmail, which updates the email address and also confirms if the new email address was typed correctly.
So far validation works also fine. Whenever email doesn't match with the confirmEmail or one of the inputs is empty, it will throw an error.
However, I want to put all this validation to the submit button, so that validation worked and errors are highlighted only once button is clicked, and update registeredEmail state if input value was valid.
Here is the code snippet and sandbox link.
import React, { useState } from "react";
function Form() {
const [registeredEmail, setRegisteredEmail] = useState("JohnDoe#gmail.com");
const [input, setInput] = useState({
email: "",
confirmEmail: ""
});
const [error, setError] = useState({
email: "",
confirmEmail: ""
});
const onInputChange = (e) => {
const { name, value } = e.target;
setInput((prev) => ({
...prev,
[name]: value
}));
validateInput(e);
};
const validateInput = (e) => {
let { name, value } = e.target;
setError((prev) => {
const stateObj = { ...prev, [name]: "" };
switch (name) {
case "email":
if (!value) {
stateObj[name] = "Please enter Email";
} else if (input.confirmEmail && value !== input.confirmEmail) {
stateObj["confirmEmail"] =
"Email and Confirm Email does not match.";
} else {
stateObj["confirmEmail"] = input.confirmEmail
? ""
: error.confirmEmail;
}
break;
case "confirmEmail":
if (!value) {
stateObj[name] = "Please enter Confirm Email.";
} else if (input.email && value !== input.email) {
stateObj[name] = "Email and Confirm Email does not match.";
}
break;
default:
break;
}
return stateObj;
});
};
const handleSubmit = (e) => {
e.preventDefault();
validateInput(e);
setRegisteredEmail(input.email);
};
return (
<>
<header>{registeredEmail}</header>
<form
style={{
display: "flex",
flexDirection: "column"
}}
>
<input
type="email"
name="email"
placeholder="address"
onChange={onInputChange}
value={input.email}
/>
{error.email && <span style={{ color: "red" }}>{error.email}</span>}
<input
onChange={onInputChange}
value={input.confirmEmail}
type="email"
name="confirmEmail"
placeholder="repeat address"
/>
{error.confirmEmail && (
<span style={{ color: "red" }}>{error.confirmEmail}</span>
)}
</form>
<button onClick={handleSubmit}>speichern</button>
</>
);
}
export default Form;
Any help will be appreciated
name is an attribute and needs function getAttribute(...) to be fetched.
Try this:
var name = e.target.getAttribute('name');
UPDATE
This won't work because the real problem is that you are checking inside the event of the button that submitted. So you don't have the inputs info and values. You should check the input state and validate those (Here you can set the errors). Then you can return a boolean to decide if the user can submit or not.
Try this:
const validateInput = () => {
if (input.email === "") {
setError({ ...error, email: "Please enter Email" });
return false;
}
if (input.email !== input.confirmEMail) {
setError({
...error,
confirmEmail: "Email and Confirm Email does not match."
});
return false;
}
// HERE YOU CAN ADD MORE VALIDATIONS LIKE ABOVE
return true;
};
const handleSubmit = (e) => {
e.preventDefault();
const isValid = validateInput();
if (isValid) {
//SubmitFunc()
}
};
You currently have your onInputChange handler run validateInput, which then sets the error. You may want to have it run validateInput only in your handleSubmit handler and only use onInputChange to handle state changes on keystrokes as you currently do.

How can we get the removed value from onChange event in react js without using event.target.value?

passwordCheck = (event) => {
console.log(event.nativeEvent, event.nativeEvent.srcElement);
let confirmPass;
if (event.nativeEvent.inputType === "insertText") {
this.state.checkConfirm.push(event.nativeEvent.data);
confirmPass = this.state.checkConfirm.join("");
} else if (event.nativeEvent.inputType === "deleteContentBackward") {
console.log("confirm check", this.state.checkConfirm);
this.state.checkConfirm.pop();
confirmPass = this.state.checkConfirm.join("");
}
console.log(confirmPass);
this.setState(
{
rePassword: confirmPass,
starRepassword: event.target.value.length,
passwordErrors: "",
},
() => {
if (this.state.newPassword === this.state.rePassword) {
console.log("matched");
} else {
this.setState({
passwordErrors: `passwords do not match`,
});
}
}
);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<input className="form-control custom_input d-flex justify-content-center"
type="text"
id="rePassword"
autoComplete="off"
placeholder="*******"
value={"*".repeat(this.state.starRepassword)}
onChange={(e) => this.passwordCheck(e)}
/>
Here I am trying to check password but my password should be in "*" characters so in else if condition I am trying to get removed character but I am failing to do it Can anyone suggest me the approcah

How to capture option selected event in Material UI autocomplete component?

I am using the autocomplete component with filterOptions to suggest the creation of a new value as shown below:
<Autocomplete
multiple
name="participant-tags"
options={people}
getOptionLabel={(option) => option.name}
renderInput={(params) => {
return (
<TextField
{...params}
variant="outlined"
label="Participants"
/>
)
}}
filterOptions={(options, params) => {
const filtered = filter(options, params);
logger.debug('filterOptions(params) %j', params)
// Suggest the creation of a new value
if (params.inputValue !== '') {
filtered.push({
inputValue: params.inputValue,
name: `Add "${params.inputValue}"`,
});
}
return filtered;
}}
onKeyDown={(e) => {
if(e.keyCode === 13) {
// TODO: select currently highlighted option
e.preventDefault()
}
}}
onChange={(e, value, reason) => {
logger.debug(e.type)
logger.debug(value)
logger.debug(reason)
e.preventDefault()
}}
/>
However, I can't figure out where to handle the selection of the "Add this option" to actually add the option?
This was solved leveraging the 'reason' parameter in the onChange handler, and the onKeyDown handler isn't needed:
filterOptions={(options, params) => {
const filtered = filter(options, params);
if (params.inputValue !== '') {
filtered.push({
inputValue: params.inputValue,
[displayOptionsField]: `Add New ${newOptionLabel} "${params.inputValue}"`,
});
}
return filtered;
}}
onChange={(e, value, reason) => {
let newOptions
if (reason==='select-option') {
const last = value.pop();
if (last.inputValue) {
newOptions = value.concat([{[displayOptionsField]: last.inputValue}])
}
else {
newOptions = value.concat([last])
}
}
if (reason==='create-option') {
const last = value.pop();
newOptions = value.concat([{[displayOptionsField]: last}])
}
if (reason==='remove-option') {
newOptions = value
}
if (newOptions) {
onChange(newOptions)
}
}}
The onChange inside the onChange handler is there as a prop from a wrapping component.

How do I pass user input ref from one component to display into another component (React)

I need help with state management in my Chat-app.
Description:
I am attempting to display the username entered from the UserModal component to my ChatScreen component. I am using the onChange function inside UserModal and I am using a switch case statement to ensure form validation. Then setting the state with name as an array and assigning the value to the name like so:
UserModal.js
onChange = e => {
e.preventDefault();
const { name, value } = e.target;
let formError = this.state.formError;
switch (name) {
case 'userName':
formError.userName =
value.length < 3 ? 'minimum 3 characters required' : '';
break;
default:
}
this.setState({ formError, [name]: value }, () =>
console.log(this.state)
);
};
onSubmit function
onSubmit = (e) => {
e.preventDefault();
if (formValid(this.state)) {
Axios.post('http://localhost:5000/api/authenticate').then(
(res) => {
if (res.data.isSuccessful === true) {
alert('Your username is: ' + this.input.value);
this.close();
} else {
alert('Error Message: ' + res.data.ErrorMessage);
}
}
);
} else {
alert(
'Error message: Please enter a username with a minimum of 3 characters'
);
}
};
Form
<form action="Main.js" className="form-inside-input" onSubmit={this.onSubmit} noValidate>
<label>Username:</label>
<input
className={formError.userName.length > 0 ? "error" : null}
type="text"
placeholder="Enter username"
name="userName"
onChange={this.onChange}
ref={(input) => (this.input = input)}
noValidate
></input>
{formError.userName.length > 0 && <span>{formError.userName}</span>}
<Button
type="submit"
positive
icon="checkmark"
labelPosition="right"
content="Let me in!"
onClick={() => {
this.onSearch();
}}
/>
</form>;
Goal:
My goal is to take what the user puts in the username field in the modal and display "{userName} has joined the chat." where userName is replaced with the input of the user, in the ChatScreen.js component within the Semantic UI fragments.
Github Link: https://github.com/George-Jindo/chat-app

Categories

Resources