cant reset input in functional component in react js - javascript

i have a function component called TextInput and return an input element:
function TextInput({ type = "text", label, name, required = false }) {
const [value, setValue] = useState("");
function handleChange(e) {
setValue(e.target.value);
}
return (
<div className={styles.footerFormInput}>
<input
type={type}
value={value}
onChange={handleChange}
name={name}
required={required}
/>
<label className={value && styles.filled} htmlFor={name}>
{label}
</label>
</div>
);
}
i am trying to reset the form, but the value doesnt reset on Customized TextInput but yes on normal/original input element.
this is my page code:
const form = useRef();
const sendEmail = (e) => {
e.preventDefault();
const inputData = e.target.elements;
if (inputData.from_email) {
if (validator.isEmail(inputData.from_email.value)) {
console.log("valid email");
} else {
// alert("Enter valid Email!");
//email error..
return;
}
}
if (inputData.full_name) {
if (
validator.isAlpha(inputData.full_name.value, ["he"], {
ignore: " ",
}) ||
validator.isAlpha(inputData.full_name.value, ["en-US"], {
ignore: " ",
})
) {
console.log("valid name");
} else {
//name error
return;
}
}
if (inputData.phone && inputData.phone.value.trim() !== "") {
if (validator.isMobilePhone(inputData.phone.value, ["he-US"])) {
console.log("valid phone");
} else {
//phone error
return;
}
}
emailjs
.sendForm(
process.env.EMAILJS_SERVICE_ID,
process.env.EMAILJS_TEMPLATE_ID,
form.current,
process.env.EMAILJS_USER_ID
)
.then(
(result) => {
//do something with success
...
form.current.reset(); //not working!!!!!!
},
(error) => {
//do something with error
}
);
};
return (
...
<form ref={form} onSubmit={sendEmail}>
<div className={styles.footerFormRow}>
<TextInput
type="input"
label='דוא"ל'
name="from_email"
/>
<TextInput
type="input"
label="שם מלא"
name="full_name"
/>
<input type="text" name="somename" />
</div>
</form>
...
)
only the somename input is reset, the others in the functional component no.
any hepl?

Related

React Multi Step Form Validation on "onBlur", "onChange" and moving to next step

I'm running field level validation on "onBlur" & "onChange" this is working as expected,
But while clicking the "Next" button without filling it's not triggering all field-level validations at one go.
Case 1: If I'm enabling autofocus to 1st field and click "Next" without filling onBlur event is triggered and It's showing a username field error. If I'm clicking the "Next" second time it's showing all the field errors.
Case 2: autofocus disabled and click "Next" without filling, It's validating and updating the state but not reflecting in DOM, form is moving to the next step.
const UserDetails = ({ nextStep, handleChange, values }) => {
const fields = ['email', 'username', 'password']
const Continue = e => {
e.preventDefault();
nextStep(fields);
}
return (
<div>
<form>
<input
type='text'
name='email'
placeholder="Email Address"
id='email'
value={values.email}
onChange={handleChange('email')}
onBlur={handleChange('email')}
autoFocus={true} // set false to replicate case 2
/>
<p
style={{ display: values.emailIsValid ? 'block' : 'none' }}
> {values.emailIsValid}
</p> <br></br>
<input
type='text'
name='username'
placeholder="Username"
id='usernaem'
value={values.username}
onChange={handleChange('username')}
onBlur={handleChange('username')}
autoFocus={false}
/>
<p
style={{ display: values.usernameIsValid ? 'block' : 'none' }}
> {values.usernameIsValid}
</p> <br></br>
<input
type='text'
placeholder="Password"
name='password'
id='password'
value={values.password}
onChange={handleChange('password')}
onBlur={handleChange('password')}
autoFocus={false}
/>
<p
style={{ display: values.passwordIsValid ? 'block' : 'none' }}
> {values.passwordIsValid}
</p> <br></br>
<button onClick={Continue}>Next</button>
</form>
</div>
);
}
const Success = ({ prevStep }) => {
const Previous = e => {
e.preventDefault();
prevStep();
}
return (
<div>
All set !!!
<button onClick={Previous}>Back</button>
</div>
);
}
class Signup extends React.Component {
state = {
step: 1,
email: '',
emailIsValid: null,
username: '',
usernameIsValid: null,
password: '',
passwordIsValid: null,
}
prevStep = () => {
const { step } = this.state;
this.setState({ step: step - 1 });
}
isValid = (field) => {
if (this.state[field] === '') {
this.setState({ [field + 'IsValid']: 'Required !!!' });
return false;
}
return true;
}
nextStep = (fields) => {
fields.forEach(this.isValid);
const { step } = this.state;
if (fields.every(field => !this.state[field + 'IsValid'])) {
this.setState({ step: step + 1 })
}
}
handleChange = input => e => {
if (e.target.value === '') {
this.setState({ [input + 'IsValid']: 'Required !!!' });
} else {
this.setState({ [input]: e.target.value });
this.setState({ [input + 'IsValid']: null });
}
}
render() {
const { step } = this.state;
const { email, emailIsValid, username, usernameIsValid, password, passwordIsValid } = this.state;
const values = { email, emailIsValid, username, usernameIsValid, password, passwordIsValid }
switch (step) {
case 1:
return (
<UserDetails
nextStep={this.nextStep}
handleChange={this.handleChange}
values={values}
/>
)
case 2:
return (
<Success
prevStep={this.prevStep}
/>
)
default:
// do nothing
}
}
}
/*
* Render the above component into the div#app
*/
ReactDOM.render(
<Signup />,
document.getElementById('app')
);
<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>
<div id="app"></app>
Can also check it in codepen:

onSubmit React js problems

I have a problem with React JS.
I have a form where the user has to pick some options and then write a number, when the user press a button named "Consultar" or press "Enter" (Intro) it suposed to send the form and show a table with the necessary information.
However, when the user press "Enter" the form information is not submitted, the only way is by pressing the button named "Consultar". I have tried using onKeyPress but it did not work.
Could it be some react bug causing the problem and not my code? If it is not something in my code, what I need is that the user can press "Enter" and that it does the same function of the "Consultar" button.
Please help, I am very new in this world of React JS. Here is the code:
const DataForm = ({
update,
setIsLoaded,
setError,
}) => {
const formatChars = { C: '[1-9]', L: '[0-9]', Z: '[0-9]?' };
const [tipoCedula, setTipoCedula] = useState('1');
const [tipoBusqueda, setTipoBusqueda] = useState('1');
const [numCedula, setNumCedula] = useState('');
const [emailAddress, setEmailAddress] = useState('');
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
tipoCedula,
tipoBusqueda,
numCedula,
emailAddress,
});
const getNumCedulaMask = (pTipoCedula) => {
if (pTipoCedula === '2') return 'C-LLL-LLLLLL';
if (pTipoCedula === '3') return 'CLLLLLLLLLLZ';
if (pTipoCedula === '4') return 'CLLLLLLLLL';
return 'C-LLLL-LLLL';
};
const getRegExFromMask = (pMask, pFormatChars) => {
let returnValue = pMask;
Object.keys(pFormatChars).map((item) => {
if (typeof returnValue.replaceAll === 'function') {
returnValue = returnValue.replaceAll(item, pFormatChars[item]);
}
return returnValue;
});
return new RegExp(`^${returnValue}$`);
};
const numCedulaMask = getNumCedulaMask(tipoCedula);
const numCedulaRegEx = getRegExFromMask(numCedulaMask, formatChars);
const emailRegEx = '^[_a-z0-9-]+(.[_a-z0-9-]+)*#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$';
const isValidNumCedula = (inputValue) => {
const replace = inputValue.replace('_', '');
if (replace.match(numCedulaRegEx)) {
return true;
}
return 'El formato no es válido';
};
const isValidEmail = (inputValue) => {
if (inputValue.match(emailRegEx)) {
return true;
}
return 'El formato no es válido';
};
const onSubmit = async (data) => {
let searchParameter = '';
if (data.tipoBusqueda === '1') {
searchParameter = data.numCedula;
} else {
searchParameter = data.emailAddress;
}
const { ssoBaseUrl } = some restricted information
const apiCall = some restricted information
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
};
setIsLoaded(true);
try {
const result = await fetch(apiCall, requestOptions);
const datos = await result.json();
setIsLoaded(false);
update('reminderResult', datos);
} catch (e) {
setError(true);
}
};
return (
<div>
<form onSubmit={handleSubmit(onSubmit)} id='formulario' data-testid='formulario-busqueda'>
<div className='form-group group_TIPO_BUSQUEDA'>
<label className='label'>Buscar por</label>
<div>
<select data-testid="search-type"
className='form-control select TIPO_BUSQUEDA'
{...register('tipoBusqueda')}
defaultValue={tipoBusqueda}
onChange={(e) => (setTipoBusqueda(e.target.value))}
>
<option value='1'>Tipo de cedula</option>
<option value='2'>Email</option>
</select></div>
</div>
{tipoBusqueda === '1' && <div className='form-group group_TIPO_CEDULA'>
<label htmlFor='tipoCedula' className='label'>Tipo de cédula</label>
<div>
<select data-testid="cedula-tipo-id"
className='form-control select TIPO_CEDULA'
{...register('tipoCedula')}
defaultValue={tipoCedula}
onChange={(e) => (setTipoCedula(e.target.value))}
>
<option value='1'>Cédula Persona Física</option>
<option value='2'>Cédula Persona Jurídica</option>
<option value='4'>Número Identificación Tributario Especial (NITE)</option>
<option value='3'>Documento Identificación Migratorio Extranjeros</option>
</select>
{errors.tipoCedula && <p className='error-message'>{errors.tipoCedula.message}</p>}
</div>
</div>
}
{tipoBusqueda === '1' && <div className='form-group group_NUM_CEDULA'>
<label htmlFor='numCedula' className='label'>Cédula</label>
<div>
<InputMask data-testid="num-cedula"
className='form-control NUM_CEDULA input'
{...register('numCedula', {
required: {
value: true,
message: 'Este campo es requerido',
},
validate: {
validValue: isValidNumCedula,
},
})}
formatChars={formatChars}
onChange={(e) => (setNumCedula(e.target.value))}
value={numCedula}
mask={numCedulaMask}
/>
{errors.numCedula && <p className='error-message' role="alert">Formato cédula incorrecto</p>}
</div>
</div>}
{tipoBusqueda === '2' && <div className='form-group'>
<label htmlFor='emailAddress' className='label'>Dirección de correo electrónico</label>
<div>
<input type="text"
data-testid="emailAddress"
className="form-control"
value={emailAddress}
{...register('emailAddress', {
required: 'Este campo es requerido',
validate: {
validValue: isValidEmail,
},
})}
onChange={(e) => (setEmailAddress(e.target.value))}
/>
{errors.emailAddress && <p className='error-message' role="alert">{errors.emailAddress.message}</p>}
</div>
</div>}
<div className='form-group'>
<button className='btn-submit float-right' type="submit" data-testid="button-ask">CONSULTAR</button>
</div>
</form>
</div>
);
};
DataForm.propTypes = {
update: PropTypes.func.isRequired,
setIsLoaded: PropTypes.func.isRequired,
setError: PropTypes.func.isRequired,
};
export default DataForm;
<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>
I did not try your code, but i saw your code and i find here something. You have to write to arrow function in onSubmit.
<form onSubmit={() => handleSubmit(onSubmit)} id='formulario' data-testid='formulario-busqueda'>
If your page getting refresh on submit, then you have to write event.preventDefault() onSubmit.
<form onSubmit={(event) => {
event.preventDefault();
handleSubmit(onSubmit);
} id='formulario' data-testid='formulario-busqueda'>
Here is a code example how to submit forms with enter key:
import React, { useState } from 'react';
export default function App() {
const [name, setName] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
console.log('form submited');
};
return (
<div>
<form onSubmit={handleSubmit} >
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</form>
</div>
);
}
....
You don't have a handleSubmit function, what you have is an onSubmit function. Therefore, in your onSubmit event listener, you are trying to call a non-existent function
<form onSubmit={handleSubmit(onSubmit)}...
This is how you should call the onSubmit function
<form onSubmit={onSubmit}...

Wrong input validation

I want to validate all of my inputs in react
My validation code looks like this:
let isValid = {
name: false,
address: false,
postcode: false,
phone: false,
email: false
};
const validateInput = (e) => {
let currentInput = e.target
if (currentInput.name === 'name') {
if (currentInput.value !== 'undefined' && currentInput.value.match(/^[a-zA-Z]+$/)) {
isValid.name = true;
} else {
isValid.name = false;
}
}
if (currentInput.name === 'address') {
if (currentInput.value !== 'undefined') {
isValid.address = true;
} else {
isValid.address = false;
}
}
if (currentInput.name === 'postcode') {
if (currentInput.value !== undefined && currentInput.value.match(/^[0-9]+[-]+[0-9]+$/) && currentInput.value.length > 4) {
isValid.postcode = true;
} else {
isValid.postcode = false;
}
}
if (currentInput.name === 'phone') {
if (currentInput.value !== 'undefined' && currentInput.value.match(/^[0-9]+$/) && currentInput.value.length > 7) {
isValid.phone = true;
} else {
isValid.phone = false;
}
}
if (currentInput.name === 'email') {
if (currentInput.value !== 'undefined' && currentInput.value.match(/^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
isValid.email = true;
} else {
isValid.email = false;
}
}
console.log(isValid)
}
For example when i type correct value in "Name" isValid.name gets value true, then when i write somethink in "address" isValid.address gets true, but isValid.name false
How to fix it?
{requiredInformations.map((el) => (
<>
<Label>{el.label}</Label>
<Input type={el.type} name={el.name} required onChange={(e) => { getInputValue(e); validateInput(e) }} />
</>
))}
I suggest you try to use react-joi library for validation React-Joi-Validation
Its easy and simple to use, and you can achieve what you are trying here in your code by just reading the first page on their npm package main page.
You need to get yourself familiar with terms like "state"
, "props", "component lifecycle", etc. Build a simple component using a guide on youtube, you can find plenty of them.
Meanwhile, here is a simple component that validates inputs:
function App() {
const [name, setName] = React.useState('');
const [address, setAddress] = React.useState('');
const isValid = React.useMemo(() => {
const result = {
name: false,
address: false,
};
if (name.match(/^[a-zA-Z]+$/)) {
result.name = true;
} else {
result.name = false;
}
if (address !== '') {
result.address = true;
} else {
result.address = false;
}
return result;
}, [name, address]);
return (
<div>
<input
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
{isValid.name ? <p>Name is valid</p> : <p>Name is invalid</p>}
<br />
<input
placeholder="Address"
value={address}
onChange={(e) => setAddress(e.target.value)}
/>
{isValid.address ? <p>Adress is valid</p> : <p>Adress is invalid</p>}
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root">
</div>

Validation check in reactjs issue

Why I am not able to see validation alert clicking on the done button when everything is empty once form open even validation checks are proper ?
Basically form opens i don't type anything and click on done button so all validation checks should work and show text 'Required.Please enter your given name.' but it is not showing ?
Where is the issue which causes the state to be blank at the end
const addSecondaryContact = inject('apptContacts')(observer((props) => {
const {
i18n, nbnContact, apptContacts, backButtonContent,
} = props;
const { updatePrimaryContact } = apptContacts;
const CMS = i18n.appointmentManager.editAppointmentContact;
const [state, setState] = useState({
data: {
firstName: '',
lastName: '',
number: '',
},
firstNameValid: '',
lastNameValid: '',
numberValid: '',
});
const validFirstName = () => {
console.log(state.data.firstName);
if (!state.data.firstName) {
console.log('frstname1');
return 'Required.Please enter your given name.';
}
if (!/^[A-Za-z]+$/.test(state.data.firstName)) {
console.log('frstname2');
return 'Invalid entry.Please use letters only.';
} if (state.data.firstName.length === 1) {
console.log('frstname3');
return 'Invalid entry.More than one character is required';
}
console.log('&&&&');
return '';
};
const validLastName = () => {
console.log('988');
if (!state.data.lastName) { console.log('lastname'); return 'Required.Please enter your given name.'; }
if (!/^[A-Za-z]+$/.test(state.data.lastName)) {
return 'Invalid entry.Please use letters only.';
} if (state.data.lastName.length === 1) {
return 'Invalid entry.More than one character is required';
}
return '';
};
const validNumber = async () => {
console.log('777');
if (!state.data.number) { return 'Required.Please enter your mobile number.'; }
if (state.data.number.substr(0, 2) !== '04') {
return 'Invalid entry.Please enter your 10-digit mobile number starting with 04.';
} if (state.data.number.length !== 10) {
return 'Invalid entry.Please enter your 10-digit mobile number starting with 04.';
} if (state.data.number.length === 1) {
return 'Invalid entry.More than one number is required';
}
return '';
};
const valid = async () => {
console.log('milan');
setState({
...state,
firstNameValid: validFirstName(),
lastNameValid: validLastName(),
numberValid: validNumber(),
});
console.log(state.firstNameValid);
console.log(state.lastNameValid);
console.log(state.numberValid);
};
const handleTextareaChange = (event) => {
console.log('%%%');
const { data } = state;
data[event.target.name] = event.target.value;
setState({
...state,
data,
});
valid();
};
const saveButton = async () => {
console.log(state);
await valid();
if (valid()) {
console.log(state.firstNameValid);
console.log(state.lastNameValid);
console.log(state.numberValid);
if (!state.firstNameValid && !state.lastNameValid && !state.numberValid) {
const personName = `${state.data.firstName} ${state.data.lastName}`;
const primaryContact = {
name: personName,
phoneNumber: state.data.number,
// updatePrimaryContact(primaryContact)
};
// updatePrimaryContact(primaryContact)
backButtonContent();
}
}
};
return (
<div>
<VerticalSpacing size={ABLE_SPACING_SIZE.spacing4x} />
<h1 tabIndex="-1" className="HeadingB mt-sheet-heading">
{CMS.heading2}
</h1>
<VerticalSpacing size={ABLE_SPACING_SIZE.spacing3x} />
<TextField id="givenName" name="firstName" label={CMS.name} onChange={handleTextareaChange} value={state.data.firstName} />
{state.firstNameValid && (
<Alert variant="error" inline>
<p>
{state.firstNameValid}
</p>
</Alert>
)}
<VerticalSpacing size={ABLE_SPACING_SIZE.spacing3x} />
<TextField id="familyName" name="lastName" label={CMS.familyName} onChange={handleTextareaChange} value={state.data.lastName} />
{state.lastNameValid && (
<Alert variant="error" inline>
<p>
{state.lastNameValid}
</p>
</Alert>
)}
<VerticalSpacing size={ABLE_SPACING_SIZE.spacing3x} />
<TextField id="mobileNumber" name="number" label={CMS.mobile} onChange={handleTextareaChange} value={state.data.number} />
{state.numberValid && (
<Alert variant="error" inline>
<p>
{state.numberValid}
</p>
</Alert>
)}
<VerticalSpacing size={ABLE_SPACING_SIZE.spacing4x} />
<ActionButton className={styles.saveCta} variant="HighEmphasis" label={CMS.saveCTA} onClick={() => saveButton()} />
</div>
);
}));
export default addSecondaryContact;
You had two main issues:
you state update is not proper - you set state on multiple occasions
you had async in your validNumber method - which causes blank output
Here is the code i modify from your code - maybe it can help you. I removed extra components in order to remove dependencies and used only plain html.
Demo: https://codesandbox.io/s/upbeat-feynman-w3odj?file=/App.js
import "./styles.css";
import React from "react";
export default function App() {
const [state, setState] = React.useState({
data: {
firstName: "",
lastName: "",
number: ""
},
firstNameValid: "",
lastNameValid: "",
numberValid: ""
});
const validFirstName = () => {
console.log(state.data.firstName);
let result = "";
if (!state.data.firstName) {
console.log("frstname1");
result = "Required.Please enter your given name.";
}
if (!/^[A-Za-z]+$/.test(state.data.firstName)) {
console.log("frstname2");
result = "Invalid entry.Please use letters only.";
}
if (state.data.firstName.length === 1) {
console.log("frstname3");
result = "Invalid entry.More than one character is required";
}
console.log("&&&&");
return result;
};
const validLastName = () => {
console.log("988");
if (!state.data.lastName) {
console.log("lastname");
return "Required.Please enter your given name.";
}
if (!/^[A-Za-z]+$/.test(state.data.lastName)) {
return "Invalid entry.Please use letters only.";
}
if (state.data.lastName.length === 1) {
return "Invalid entry.More than one character is required";
}
return "";
};
const validNumber = () => {
console.log("777");
if (!state.data.number) {
return "Required.Please enter your mobile number.";
}
if (state.data.number.substr(0, 2) !== "04") {
return "Invalid entry.Please enter your 10-digit mobile number starting with 04.";
}
if (state.data.number.length !== 10) {
return "Invalid entry.Please enter your 10-digit mobile number starting with 04.";
}
if (state.data.number.length === 1) {
return "Invalid entry.More than one number is required";
}
return "";
};
const valid = async () => {
console.log("milan");
setState({
...state,
firstNameValid: validFirstName(),
lastNameValid: validLastName(),
numberValid: validNumber()
});
console.log(state.firstNameValid);
console.log(state.lastNameValid);
console.log(state.numberValid);
};
const handleTextareaChange = (event) => {
let validRes = "";
let key = "";
if (event.target.name === "firstName") {
validRes = validFirstName();
key = "firstNameValid";
}
if (event.target.name === "lastName") {
validRes = validLastName();
key = "firstNameValid";
}
if (event.target.name === "number") {
validRes = validNumber();
key = "numberValid";
}
console.log("234", validRes);
setState({
...state,
data: { ...state.data, [event.target.name]: event.target.value },
// [key]:
firstNameValid: validFirstName(),
lastNameValid: validLastName(),
numberValid: validNumber()
});
// valid();
};
const saveButton = async () => {
console.log(state);
await valid();
if (valid()) {
console.log(state.firstNameValid);
console.log(state.lastNameValid);
console.log(state.numberValid);
}
};
return (
<div>
<h1 tabIndex="-1" className="HeadingB mt-sheet-heading">
'CMS.heading2'
</h1>
<input
type="text"
id="givenName"
name="firstName"
label="CMS.name"
onChange={handleTextareaChange}
value={state.data.firstName}
/>
{state.firstNameValid && <p>{state.firstNameValid}</p>}
<input
type="text"
id="familyName"
name="lastName"
label="CMS.familyName"
onChange={handleTextareaChange}
value={state.data.lastName}
/>
{state.lastNameValid && <p>{state.lastNameValid}</p>}
<input
type="text"
id="mobileNumber"
name="number"
label="CMS.mobile"
onChange={handleTextareaChange}
value={state.data.number}
/>
{state.numberValid && <p>{state.numberValid}</p>}
<button
variant="HighEmphasis"
label="CMS.saveCTA"
onClick={() => saveButton()}
/>
</div>
);
}

Textfields component number validation React js

I have 3 Textfields, what I want to do is just to accept number so if someone put text and click continue the application should display an error saying that just numbers are allowed.
The following code displays an error message if the Textfield is empty and thats ok but the other validation to check if the user inputs text or numbers is pending and I'm stucked.
import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Divider from 'material-ui/Divider';
import cr from '../styles/general.css';
export default class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
buy_: '',
and_: '',
save_: '',
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event, index, value) {
this.setState({value});
}
clear() {
console.info('Click on clear');
this.setState({
buy_: '',
and_: '',
save_: ''
});
}
validate() {
let isError = false;
const errors = {
descriptionError: ''
};
if (this.state.buy_.length < 1 || this.state.buy_ === null) {
isError = true;
errors.buy_error = 'Field requiered';
}
if (this.state.and_.length < 1 || this.state.and_ === null) {
isError = true;
errors.and_error = 'Field requiered';
}
if (this.state.save_.length < 1 || this.state.save_ === null) {
isError = true;
errors.save_error = 'Field requiered';
}
this.setState({
...this.state,
...errors
});
return isError;
}
onSubmit(e){
e.preventDefault();
// this.props.onSubmit(this.state);
console.log('click onSubmit')
const err = this.validate();
if (!err) {
// clear form
this.setState({
buy_error: '',
and_error: '',
save_error: ''
});
this.props.onChange({
buy_: '',
and_: '',
save_: ''
});
}
}
render() {
return (
<div className={cr.container}>
<div className ={cr.boton}>
<Divider/>
<br/>
</div>
<div className={cr.rows}>
<div>
<TextField
onChange={(e) => {this.setState({buy_: e.target.value})}}
value={this.state.buy_}
errorText={this.state.buy_error}
floatingLabelText="Buy"
/>
</div>
<div>
<TextField
onChange={(e) => {this.setState({and_: e.target.value})}}
value={this.state.and_}
errorText={this.state.and_error}
floatingLabelText="And"
/>
</div>
<div>
<TextField
onChange={(e) => {this.setState({save_: e.target.value})}}
value={this.state.save_}
errorText={this.state.save_error}
floatingLabelText="Save"
/>
</div>
</div>
<div className={cr.botonSet}>
<div className={cr.botonMargin}>
<RaisedButton
label="Continue"
onClick={e => this.onSubmit(e)}/>
</div>
<div>
<RaisedButton
label="Clear"
secondary ={true}
onClick={this.clear = this.clear.bind(this)}
/>
</div>
</div>
</div>
);
}
}
Can someone help me on this please.
Thanks in advance.
You can prevent users from input text by using this :
<TextField
onChange={(e) => {
if(e.target.value === '' || /^\d+$/.test(e.target.value)) {
this.setState({and_: e.target.value})
} else {
return false;
}
}}
value={this.state.and_}
errorText={this.state.and_error}
floatingLabelText="And"
/>
The TextField component can restrict users to entering text using the JavaScript test method:
<TextField
onChange={(e) => {
if(e.target.value == '' || (/\D/.test(e.target.value))) {
this.setState({and_: e.target.value})}
}
else {
return false;
}
}
value={this.state.and_}
errorText={this.state.and_error}
floatingLabelText="And"
/>
Try adding this code in your validate function.
You can use regex to validate your fields for text or numbers like :
import * as RegExp from './RegExpression';
validate() {
let isError = false;
const errors = {
descriptionError: ''
};
if (this.state.buy_ && !RegExp.NAME.test(this.state.buy_)) {
// validation check if input is name
isError = true;
errors.buy_error = 'Invalid name';
}
if (this.state.and_ && !RegExp.NUMBER.test(this.state.and_)) {
// validation check if input is number
isError = true;
errors.and_error = 'Invalid Number';
}
this.setState({
...this.state,
...errors
});
return isError;
}
In RegexExpression file add these validations like this :
export const NAME = /^[a-z ,.'-()"-]+$/i;
export const NUMBER = /^[0-9]*$/ ;
You are not initialising error object in state but accessed in TextField as this.state.and_error. Either you should initialise error in constructor like this.state = { and_error: "" } or initialise error object as
this.state = {
error: {
and_error: "",
buy_error: "",
save_error: ""
}
}
So in your TextField
<TextField
onChange={(e) => {
if(e.target.value === "" || (/\D/.test(e.target.value))) {
this.setState({and_: e.target.value})}
}
else {
return false;
}
}
value={this.state.and_}
errorText={this.state.error.and_error} // If initialised error string access as this.state.and_error
floatingLabelText="And"
/>
Your validate function will be like
validate() {
let isError = false;
const errors = this.state.errors;
if (this.state.buy_.toString().length < 1 || this.state.buy_ === null) {
isError = true;
errors.buy_error = 'Field requiered';
}
if (this.state.and_.toString().length < 1 || this.state.and_ === null) {
isError = true;
errors.and_error = 'Field requiered';
}
if (this.state.save_.toString().length < 1 || this.state.save_ === null) {
isError = true;
errors.save_error = 'Field requiered';
}
this.setState({errors});
return isError;
}
Hope this will heps you!
You can use react-validation for all validation and set rules for validation

Categories