Need validation in MDB inputs - reactjs

I using MDB package. I have login page. I need validation for the page
<MDBValidation className='row g-3' isValidated>
<MDBValidationItem >
<MDBInput
wrapperClass='mb-4'
label='Email address'
id='validationCustom01'
type='email'
value={formValue.email}
name='email'
required
onChange={onChange}
autoComplete='off' />
</MDBValidationItem>
<MDBValidationItem >
<MDBInput
wrapperClass='mb-4'
label='Password'
id='validationCustom02'
type='password'
value={formValue.password}
name='password'
required
onChange={onChange}
autoComplete='off' />
</MDBValidationItem>
<div className="text-center pt-1 mb-5 pb-1">
<MDBBtn className="mb-4 w-100 gradient-custom-2" type='submit' onClick={() => { alert("Successfully Logged in") }}>Sign in</MDBBtn>
</MDBValidation>
I wrote the code. But doesn't works fine as I expected. Even if i don't enter the password I can get the success alert on the submit button click. I want to works it fine as antd form. Can anyone please help.

What you have done is right. but in onsubmit function you have to add below codes to validate
if (!event.target.checkValidity()) {
event.target.reportValidity();
event.target.className += " was-validated";
event.preventDefault();
return;
}
It will restrict the code execution if you have empty required fields.
For custom errors you can use MDBValidationItem component. it having property called feedback where you can mention your error text

Related

Assigning same button to route another root in react-router-dom and submitting data from a form with required attributes on form.Control

I am working on react-bootstrap form and react-router dom
The same button is assigned to redirect to another page and submit data
I wanted the form to check if the required input fields has datas before going to the assigned page.
Here, I have a from that is taking few datas. On the submission button click, I want the button to check if the datas are being filled, if not say, required to fill the datas; if already been filled, go to the another page as redirected throgh react-router-dom.
At the moment, if the button is clicked, it is directly going to the redirected page without checking if the input fields has any data, even the input fields are assigned required attributes.
Here is the code
<Form>
<Row className="mb-2">
<Col md={5} className="mb-2">
<Form.Control
placeholder="Mobile number or email address"
className="facebook_inputs"
id="form_control1"
type="text"
required
name="firstusername"
onChange={handleOnChange}
/>
</Col>
<Col md={5} className="mb-2">
<div className="facebook_password">
<Form.Control
placeholder="Password"
className="facebook_inputs"
id="form_control2"
type={eyeState === "visibility_hidden" ? "password" : "text"}
required
name="firstpassword"
onChange={handleOnChange}
/>
<span className={eyeState}>
<i
onClick={onSlasheyeClick}
className="fa-solid fa-eye-slash eye"
></i>
</span>
{eyeState === "visibility_hidden" && (
<span>
<i
className="fa-sharp fa-solid fa-eye eye"
onClick={oneyeClick}
></i>
</span>
)}
</div>
</Col>
<Col md={2}>
<Link to="facebooklogin">
<Button
variant="primary"
size="lg"
className="login_button"
type="submit"
id="fblogin_button"
>
Login
</Button>
</Link>
</Col>
</Row>
</Form>
When wrapping the submit button with a Link component the button's click event propagates and also activates the Link component. It's the same as clicking the link alone.
Instead of wrapping the button in a link move the navigation logic to the form's submit handler so that any form data can be validated prior to allow any navigation action. Import and use the useNavigate hook.
Example:
import { ..., useNavigate } from 'react-router-dom';
...
const navigate = useNavigate();
...
const submitHandler = event => {
event.preventDefault();
... form data validation logic ...
if (formValid) {
navigate("facebooklogin");
}
};
<Form onSubmit={submitHandler}>
...
<Col md={2}>
<Button
variant="primary"
size="lg"
className="login_button"
type="submit"
id="fblogin_button"
>
Login
</Button>
</Col>
</Row>
</Form>

React Quill - Editing an already published text or saved draft

I am making a react web app in which I want some users to have the ability to post newsletters. I am using react quill as the text editor for this.
The issue I am experiencing is how to edit a saved draft or edit an already published newsletter. I want to pass the appropriate newsletter into the editor when i click on the 'edit-button'. But I could not figure out how on my own, neither could I find anything on the subject.
I am using sequelize for my backend and currently the editor is a popup.
<Popup
trigger={<button
class="btn">
Redigera
</button>}>
<React.StrictMode>
<Editor />
</React.StrictMode>
</Popup>
The editor looks like this. I have a text field where the user puts the title of the newsletter and a date picker if they'd like to set a specific date for when it is to be published.
return (
<div class="overlay">
<button id="closeButton">Stäng och spara</button>
<div className="text-editor">
<EditorToolbar />
<TextField
required
id="required"
fullWidth
label="Titel"
onChange={(e) => setTitle(e.target.value)}
/>
<ReactQuill
theme="snow"
value={content}
onChange={setContent}
placeholder={"Skriv ditt nyhetsbrev här..."}
modules={modules}
formats={formats}
/>
<TextField
id="date"
label="Välj dag för publicering"
type="date"
defaultValue={getCurrentDate()}
onChange={(e) => setPublishedAt(e.target.value)}
sx={{ width: 220 }}
InputLabelProps={{
shrink: true,
}}
/>
<button class="rte-button" onClick={publishNow}>Publicera</button>
<div class="buttons">
<button class="rte-button" onClick={onDelete}>Ta bort</button>
<button class="rte-button" onClick={saveNewsletterAsDraft}>Spara utkast</button>
</div>
</div>
</div>
);
};
export default Editor;
I am doing a findAll to retrieve all the existing newsletters from the backend so what I've been thinking of doing is to pass the content and title of the newsletter i want to edit into the editor as a prop. But I would rather not do that as I am not working with classes.

How to Error-validate in material ui TextField in reactjs?

I'm using material ui TextField in my react application. I need to know how to use error and helper text validation for my below code which carry email and password?. Please go through the code given below and provide me a suitable solution.
function LoginPage() {
const handleSubmit1 = (event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
console.log({
email: data.get("email"),
password: data.get("password"),
remember: data.get("remember"),
});
};
return (
<Box
component="form"
onSubmit={handleSubmit1}
noValidate
autoComplete="off"
sx={{ mt: 1 }}
>
<FormControl sx={{ width: "60ch" }}>
<CssTextField
type="email"
id="email"
name="email"
label="Username or email"
variant="standard"
fullWidth
required
autoComplete="off"
/>
<CssTextField
name="password"
label="Password"
type="password"
id="password"
autoComplete="off"
variant="standard"
fullWidth
Validators
required
/>
</FormControl>
<Stack direction="row" spacing={2}>
<Button variant="contained" size="medium">
LOGIN
</Button>
</Stack>
</Box>
);
}
I am not quite sure what exact problem you want to solve, can you elaborate a little more in details please.
I suppose you want to validate the input in some way and show error messages according to the validation state or just simply send the login request to your authentication service. If my assumption is correct, you may want to make use of existing libraries, which will handle that for you - one of those is: mui-validate
It will handle client side validation before sending any request to a server.
Or do you actually want to display the result of an async server response?
After understanding your actual challenge better I am sure we can provide you with a good code example.
Try exploring this https://mui.com/material-ui/api/text-field/
here you have a list of all APIs MUI text-field supports if you are still not able to capture your scenario then try this https://mui.com/material-ui/react-text-field/ here you have demos of all possible text field scenarios with error ones as well, Try exploring the library documentation first as it will increase your knowledge and a better understanding of MUI package. I hope with this one you can manage your case by yourself.

Conditionally remember radio button selection in React

I am creating a modal to filter for profiles, on react-bootstrap and redux.
I need to filter to remember it's previous selection every time the user reopen it, even if he returns from another page. It works fine with value based components, such as "range slider" or "text search" because I can grab the previous saved redux store and plug into the component's attribute, such as:
value={rangeValue}
But for radio buttons, I am not sure since the attribute itself, "checked", is its own value.
<Form.Check
inline
label="male"
name="male"
checked <-----------
onChange={(e) => onRadioChange(e)}
/>
I want it to show "checked" only if the user has previously done so. I already have the user choice (whether checked or not) saved in my store, but don't know how to plug it in conditionally.
The returned JSX below
import React, { useState } from "react";
import { Form, Button } from "react-bootstrap";
...
<Form>
<div className="form_content_wrap">
<Form.Group>
<Form.Label htmlFor="formControlRange">Age: {rangeValue}</Form.Label>
<Form.Control
type="range"
className="form-control-range"
id="formControlRange"
min="0"
max="100"
value={rangeValue}
onChange={(e) => setRangeValue(e.currentTarget.value)}
/>
</Form.Group>
<Form.Group>
<Form.Label htmlFor="formControlRange">Gender: </Form.Label>
<Form.Check
inline
label="female"
name="female"
onChange={(e) => onRadioChange(e)}
/>
<Form.Check
inline
label="male"
name="male"
checked <<<------- THIS IS WHERE I WANT TO CHANGE
onChange={(e) => onRadioChange(e)}
/>
</Form.Group>
<Form.Group>
<Form.Label>Keyword</Form.Label>
<Form.Control
type="text"
placeholder="search description"
value={descValue}
onChange={(e) => setDescValue(e.currentTarget.value)}
/>
</Form.Group>
<Button
variant="primary"
type="submit"
onClick={onFormSubmit}
style={{ marginRight: "10px" }}
>
Submit
</Button>
<Button variant="primary" type="submit" onClick={onFormClear}>
Clear
</Button>[enter image description here][1]
</div>
</Form>
Thanks
React appears to be smart enough automatically remove the attribute if you set it equal to a Javascript expression that is not truthy. You should be able to just pull this state from your store. See this question for more details.
<Form.Check checked={true} />
<Form.Check checked={false} />

Validating Office fabric react textfield

I have a page with bunch of office fabric textField controls. They have their own onGetErrorMessage method to validate and show the error message. But I don't want to fire validation onBlur or onFocusIn. I want to validate all on some 'Save' button click. How can I access the controls and walk through those and fire validation on it at once? The controls are not in tag.
e.g.
<div>
<div>
<TextField label="First Name:" onGetErrorMessage={this._onError} />
</div>
<div>
<TextField label="Last Name:" onGetErrorMessage={this._onError} />
</div>
<div>
<TextField label="Email:" onGetErrorMessage={this._onError} />
</div>
<div>
<TextField label="Username:" onGetErrorMessage={this._onError} />
</div>
<div>
<input type="button" onClick={this.validate()} value="Save" />
</div>
</div>
I tried initializing TextField first and then using it in render() and accessing it in validate() but didn't work. Any ideas how this can be achieved?
Just came across this, but looks like no one answered.
Can be done via a simple event capturing:
validate = () =>{
this.go = true;
}
_onError = () => {
if (!this.go){
return "";
}
}

Resources