I'm building a portal where students from only 6 universities can participate so I need a way to limit the email address type to these 6 universities for example emails ending with #mit.edu
How do I implement this in React with the form validation set to characters and on clicking on of these formats from the dropdown the email is saved as such for example in the email input field if you write cassandra and select #mit.edu from the dropdown the email becomes cassandra#mit.edu
This is how my login component looks like
`
function LogIn() {
const [password, setPassword] = React.useState("");
const [email, setEmail] = React.useState("");
const [err, setErr] = React.useState(null);
const history = useHistory();
const handleSubmit = async (event, password, email) => {
event.preventDefault();
var myHeaders = new Headers();
myHeaders.set('Authorization', 'Basic ' + encode(email + ":" + password));
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
let response;
try {
response = await fetch (`${APIlink}/users`, requestOptions)
} catch (err) {
setErr("Incorrect Password. Please Retry.");
return;
}
const result = await response.text();
//console.log(result);
const json = JSON.parse(result);
//console.log(json);
//console.log(response);
if (response.status===200) {
setErr(null);
localStorage.setItem('isAuthenticated', true);
//context.updateToken(JSON.stringify(json.data));
history.push("/Projects");
} else {
setErr(json.error);
console.log(json.error);
}
};
return (
<div>
<Header />
<div className="register row justify-content-center align-items-center">
<div className = "w-50 p-3">
<h1>Log in</h1>
<Link to="/Register">or create a new account</Link>
<br></br>
<br></br>
<form>
<div className="input-group mb-3">
<input type="text" id="email"
value={email}
onChange= {(event) => {
setErr("");
setEmail(event.target.value); }}
className="form-control form-control-lg" placeholder=" institute email" aria-label="institute-email" aria-describedby="basic-addon2"/>
</div>
<small
style={{ color: "red", height: "10px", display: "inline-block" }}
>
{err == "user not found" ? "Account doesn't exist" : ""}
</small>
<div className="input-group mb-3">
<input type="text" id="password"
value={password}
onChange={(event) => {
setPassword(event.target.value);
setErr("");
}}
className="form-control form-control-lg" placeholder="password" aria-label="password" aria-describedby="basic-addon2"/>
</div>
<small
style={{ color: "red", height: "10px", display: "inline-block" }}
>
{err == "incorrect password"
? "Incorrect Password"
: err == "Username and Password can't be empty"
? err
: ""}
</small>
<Submit
//loginState={loginState}
onClick={(event) => {
event.preventDefault();
if (email != "" && password != "") {
handleSubmit(event, password, email);
} else {
setErr("Username and Password can't be empty");
}
}}
>
{" "}
Log In
</Submit>
</form>
</div>
</div>
</div>
)
}
export default LogIn;
`
You can use regex to validate email. Add this validateEmail function right after clicking on submit and pass the email that you want to validate, then proceed further only if it returns true (it will return true if it matches the pattern).
function validateEmail(email)
{
var regex = /^[^\s#]+#mit\.edu$/;
var result = regex.test(email);
if(result == true){
//Proceed further
}
else{
console.log("Enter correct email address!")
}
}
According to this regex, it will return true only if there is exact '#mit.edu' right after any string. Like:-
'anystring#mit.edu' //Returns true
'anystring#mit.com' //Returns false
'anystring#mit.edu.com' //Returns false
You can do this similarly with other domains just replace mit.edu with any other domain or if the domain has more length then simply add '\.domain' for example: -
var regex = /^[^\s#]+#mit\.edu\.com$/;
This will return true if email is 'anystring#mit.edu.com'.
EDIT: A slight correction. Remove '+' after mit and edu, as it returns true on these conditions: -
anystring#mitt.edu
anystring#mit.eduu
Check the regex above now, it should work perfectly.
Related
For my react app, I need a 'Update Article' component. I am initially filling the form with fetching the values from the existing article in backend. But when I click Submit button without changing anything It's still returning errors. What could be the problem?
This is the code:
const [articleTitle, setArticleTitle] = useState("");
..otherStates
const [getArticleRes, getArticleReq] = useApi();
const {
register,
handleSubmit,
formState: { errors, }
} = useForm();
useEffect(() => {
getArticleReq(urls.articlesUrl + "/" + articleId, { method: "GET" });
}, []);
useEffect(() => {
if (getArticleRes.status) {
if (getArticleRes.status === 200) {
const { title, body, imguri } = getArticleRes.data.result;
setArticleTitle(title);
setArticleBody(body);
setImageData(imguri);
} else if (getArticleRes.status === 400) {
console.log("SIKINTI BÜYÜK");
} else {
}
}
}, [getArticleRes.data, getArticleRes.status]);
//Updating the article here. Totatlly works but needed to delete for the code limitation
return (
<div>
<form onSubmit={handleSubmit(editArticle)}>
<TextField
sx={{ width: "100%" }}
margin="normal"
id="articleTitle"
name="articleTitle"
label="Title"
variant="outlined"
value={articleTitle}
{...register("articleTitle", {
required: true,
minLength: 8,
onChange: (e) => setArticleTitle(e.target.value),
})}
/>
{ errors.articleTitle && errors.articleTitle.type === "required" && (
<span className={classes.errorMessage}>Title is Required</span>
)}
{ errors.articleTitle && errors.articleTitle.type === "minLength" && (
<span className={classes.errorMessage}>
Minimum characters 8 required
</span>
)}
...and other textfields
<Button
type="submit"
variant="contained"
>
Submit Article
</Button>
</form>
</div> ```
[This is the situation when I try to submit with changing anything with the existing fetched data][1]
[1]: https://i.stack.imgur.com/j0U8h.png
i'm trying to validate my form but always get the same error,
this the code of the form:
import React from "react";
import zxcvbn from "zxcvbn";
import logo from "../images/milinus.png";
import useForm from "./useForm";
function Signup() {
//function for validation of the submited data from the form
const validation = (values) => {
let errors = {};
//name validion
if (!values.name.trim()) {
errors.name = "Name is required";
}
//last name validtion
if (!values.lastname.trim()) {
errors.lastname = "Username is required";
}
//email validtion
if (!values.email.trim()) {
errors.email = "Email is required";
} else if (!/\S+#\S+\.\S+/.test(values.email)) {
errors.email = "Email is invalid";
}
//password validtion
if (!values.pass.trim()) {
errors.pass = "pass is required";
} else if (values.pass < 8) {
errors.pass = "PassWord need to be 8 characters or more";
}
//pass_conf
if (!values.pass_conf.trim()) {
errors.pass_conf = "pass_conf is required";
} else if (values.pass_conf == !values.pass) {
errors.pass_conf = "pass_conf is not match the Password";
}
return errors;
}
//custom hook for the form
const { hadleChange, values, handleSubmit, errors } = useForm(validation);
//function that conforme and indicaite the score of the pass word
const confirm_ps = (e) => {
const weak = document.querySelector(".weak");
const muduim = document.querySelector(".muduim");
const strong = document.querySelector(".strong");
const indicater = document.querySelector(".indicater");
let test = zxcvbn(e.target.value);
weak.setAttribute("style", "background-color:white");
muduim.setAttribute("style", "background-color:white");
strong.setAttribute("style", "background-color:white");
indicater.innerHTML = "";
console.log(test.score);
if (test.score === 0 || test.score === 1) {
if (e.target.value == !null) {
weak.setAttribute("style", "background-color:white");
muduim.setAttribute("style", "background-color:white");
strong.setAttribute("style", "background-color:white");
indicater.innerHTML = "";
}
console.log(e.target.value);
weak.setAttribute("style", "background-color:red");
indicater.innerHTML = "Weak";
} else if (test.score === 2 || test.score === 3) {
weak.setAttribute("style", "background-color:yellow");
muduim.setAttribute("style", "background-color:yellow");
indicater.innerHTML = "Meduim";
} else if (test.score === 4) {
weak.setAttribute("style", "background-color:green");
muduim.setAttribute("style", "background-color:green");
strong.setAttribute("style", "background-color:green");
indicater.innerHTML = "Strong";
}
};
return (
<div className="signup">
<div className="logo">
<img src={logo} alt="logo" />
<p>CREER UN COMPTE</p>
</div>
<div className="inputs">
<form className="form" onSubmit={handleSubmit}>
<div className="form-input">
<input
type="text"
name="name"
id="name"
placeholder="Nom"
value={values.name}
onChange={hadleChange}
/>
<p className="errorname">{errors.name}</p>
</div>
<div className="form-input ">
<input
type="text"
name="lastname"
id="lastname"
placeholder="Prenom"
value={values.lastname}
onChange={hadleChange}
/>
<p className="errorlastname"></p>
</div>
<div className="form-input">
<input
type="text"
id="username"
name="username"
placeholder="Username"
value={values.username}
onChange={hadleChange}
/>
<p className="errorusername"></p>
</div>
<div className="form-input">
<input
type="text"
id="email"
name="email"
placeholder="Email"
value={values.email}
onChange={hadleChange}
/>
<p className="erroremail"></p>
</div>
<div className="form-input">
<input
type="password"
id="pass"
name="pass"
placeholder="Mote de pass"
onChange={confirm_ps}
/>
<p className="errorpassword"></p>
</div>
<div className="form-input">
<input
type="password"
id="pass_conf"
className="conform"
name="pass_conf"
placeholder="conform le mote de pass"
value={values.pass_conf}
onChange={hadleChange}
/>
<p className="errorpass_conf"></p>
</div>
<div className="progress">
<span className="weak"></span>
<span className="muduim"></span>
<span className="strong"></span>
</div>
<div className="indicater"></div>
<div className="wornings">
<ul>
<li>Letters majuscule et minuscule</li>
<li>Plus de 8 characters</li>
<li>Contiens au moin un chiffers ou symbol</li>
</ul>
</div>
<button type="submite" className="signup-btn">
S'INSCRIRE AND ACCEPTER
</button>
</form>
</div>
</div>
);
}
export default Signup;
and this the code for the custom hook:
import { useState, useEffect } from "react";
const useForm = (callback,validation) => {
const { values, setValues } = useState({
name: "",
lastname: "",
username: "",
email: "",
pass: "",
pass_conf: "",
});
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
const handleChange = (e) => {
const { name, value } = e.target;
setValues({
...values,
[name]: value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
setErrors(validation(values));
setIsSubmitting(true);
};
useEffect(() => {
if (Object.keys(errors).length === 0 && isSubmitting) {
callback();
}
}, [errors]);
return { handleChange, handleSubmit, values, errors };
};
export default useForm;
when i click on the submit button i get this errors:
TypeError: validation is not a function
22 |
23 | const handleSubmit = (e) => {
24 | e.preventDefault();
25 | setErrors(validation(values));
| ^ 26 | setIsSubmitting(true);
27 | };
You are setting two parameters for the hook - a callback function and validation function, and you are only passing the validation function
useForm(validation)
Please pass the callback function first and then that vaildation function
Because you pass only callback, not validation. You need decalre callBack and pass it into useForm
const callBack = () => {...};
useForm(callBack, validation);
Your useForm receives two params where you only give it one in the callback
const useForm = (callback,validation)
As a result, it got error here:
setErrors(validation(values));
I think your logic is somewhat not clear.
const { hadleChange, values, handleSubmit, errors } = useForm(validation);
Whatever, you passed validation as a callback here.
How about changing it as follow.
const useForm = (validation, callback) => {
To use the callback, you can define the callback here.
const { hadleChange, values, handleSubmit, errors } = useForm(validation, function() {... callback here});
I'm using reactjs as my development tool and mongoDB as my backend database.
I have my backend react code as following:
const express = require("express");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const { User, VerificationCode } = require("../models");
const { isLoggedIn, getLoggedInUserId, generateRefreshToken } = require("./middlewares");
const sendVerificationEMail = require("./bin/send_email").sendVerificationEmail;
require("dotenv").config();
const router = express.Router();
router.post("/register", async (req, res, next) => {
const { email, username, password, first_name, last_name } = req.body;
try {
// Check if the email is duplicating
let existingUser = await User.findOne({ where: { email } });
if (existingUser) {
return res.status(409).json({
success: false,
message: "User already exists.",
});
}
existingUser = await User.findOne({ where: { username } });
if (existingUser) {
return res.status(409).json({
success: false,
message: "Same nickname user exists.",
});
}
const hash = await bcrypt.hash(password, 12);
await User.create({
email,
username,
password: hash,
first_name,
last_name,
});
return res.status(200).json({
success: true,
message: "Signup successful.",
});
} catch (error) {
return res.json({
success: false,
message: "Signup failed.",
});
}
});
// Login
// Create token and return to user (httpOnly cookies)
router.post("/login", async (req, res, next) => {
const { email, password } = req.body;
// Make a inquiry of the user through email
try {
const user = await User.findOne({ where: { email }, raw: true });
if (!user) {
return res.status(401).json({
success: false,
message: "No member exists.",
});
}
// Check password
const isMatch = await bcrypt.compare(password, user.password);
if (isMatch) {
// If the password matches,create JWT payload
const payload = {
uid: user.id,
};
// JWT token create
const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: req.app.get("jwt_expiration") });
// New refresh token and create expiration for it
let refresh_token = generateRefreshToken(req, user.id);
let refresh_token_maxage = new Date() + req.app.get("jwt_refresh_expiration");
// Browswer httpOnly cookie setting
res.cookie("access_token", token, {
// secure: true,
httpOnly: true,
});
res.cookie("refresh_token", refresh_token, {
// secure: true,
httpOnly: true,
});
// Save the account id as key and save in Redis server
req.client.set(
user.id,
JSON.stringify({
refresh_token: refresh_token,
expires: refresh_token_maxage,
}),
req.client.print
);
return res.json({
success: true,
uid: user.id,
message: "Login Successful",
});
} else {
return res.status(401).json({
success: false,
message: "Password's don't match.",
});
}
} catch (error) {
console.error(error);
res.status(401).json({
success: false,
message: "Login Error",
});
}
});
module.exports = router;
And I have my Login frontend code as following: (Login.js)
import React, { Component } from "react";
import login from "../picture/login.png";
import Form from "react-bootstrap/Form";
import axios from "axios";
export default class SignUp extends Component {
render() {
return (
<div style = {{
backgroundColor:'#f7feff'
}}>
<div class="container h-100">
<div class="row h-100 justify-content-center align-items-center">
<form class="col-6">
<br/><br/><br/>
<h2>Login</h2>
<hr />
<div class="row h-100 justify-content-center align-items-center">
<img src = {login}
width = '550'
height = '200'
alt='Login2'/>
</div>
<Form.Group controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email" />
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" placeholder="Enter password" />
</Form.Group>
<Form.Group controlId="formBasicCheckbox">
<Form.Check type="checkbox" label="Remember me" />
</Form.Group>
<button type="submit" className="btn btn-info btn-block">Submit</button>
<div className = "App-wrapper">
<p className="forgot-password text-right">
<a href="signup"to="/signup">
Sign Up | </a>
<a href="password"to="/pasword">
Find Password</a>
</p>
</div>
</form>
</div>
</div>
</div>
);
}
}
My Signup frontend code is:(Signup.js)
import React, { Component } from "react";
import Form from "react-bootstrap/Form";
import welcome from "../picture/welcome.png";
export default class SignUp extends Component {
render() {
return (
<div style = {{
backgroundColor:'#f7feff'
}}>
<div class="container h-100">
<div class="row h-100 justify-content-center align-items-center">
<form class="col-6">
<br/><br/><br/>
<h2>Sign Up</h2>
<hr />
<div class = "row h-100 justify-content-center align-items-center">
<img src = {welcome}
width = '550'
height = '200'
alt='signup'/>
</div>
<Form.Group controlId="formBasicEmail">
<Form.Label>*Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email" />
</Form.Group>
<Form.Group controlId="formBasicUsername">
<Form.Label>*Username</Form.Label>
<Form.Control placeholder="Enter username" />
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>*Password</Form.Label>
<Form.Control type="password" placeholder="Enter password" />
</Form.Group>
<Form.Group controlId="formBasicFirstname">
<Form.Label>*Firstname</Form.Label>
<Form.Control placeholder="Enter firstname" />
</Form.Group>
<Form.Group controlId="formBasicLastname">
<Form.Label>*Lastname</Form.Label>
<Form.Control type placeholder="Enter lastname" />
</Form.Group>
<Form.Group controlId="formBasicTelephone">
<Form.Label>Telephone</Form.Label>
<Form.Control type="number"placeholder="Enter telephone number"/>
</Form.Group>
<Form.Text className="text-muted">
Fields that are marked with asterisk(*) are compulsory.
</Form.Text>
<button type="submit" className="btn btn-info btn-block">Sign Up</button>
<p className="forgot-password text-right">
Already registered? sign in?
</p>
</form>
</div>
</div>
</div>
);
}
}
I really don't know how to connect backend and frontend using axios. The login server url is localhost:8002/auth/login and for signup: localhost:8002/auth/signup
In your React component, you have to make a function that uses axios to call the backend, and then add that as a onClick handler to the submit button.
To make a request with axios you have to use the functions available on the axios module. In your case, this could look something like this:
function onSubmit() {
axios.post('localhost:8002/auth/login',
{username: username,
password: password });
}
Be aware that axios.post returns a promise, so you would have to await it/use .then to get the response from the backend. When you have the function, you can attach it to your login button like this:
<button type="submit" className="btn btn-info btn-block" onClick={onSubmit}>Submit</button>
EDIT: And the username and password values are of course the values that the user has entered via the input fields. You can store these in the state of the component.
I have the following React Component, which holds a form with two inputs and a button.
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
email: null,
password: null
}
}
emailInputChanged = (e) => {
this.setState({
email: e.target.value.trim()
});
};
passwordInputChanged = (e) => {
this.setState({
password: e.target.value.trim()
});
};
loginButtonClicked = (e) => {
e.preventDefault();
if (!this.isFormValid()) {
//Perform some API request to validate data
}
};
signupButtonClicked = (e) => {
e.preventDefault();
this.props.history.push('/signup');
};
forgotPasswordButtonClicked = (e) => {
e.preventDefault();
this.props.history.push('/forgot-password');
};
isFormValid = () => {
const {email, password} = this.state;
if (email === null || password === null) {
return false;
}
return isValidEmail(email) && password.length > 0;
};
render() {
const {email, password} = this.state;
return (
<div id="login">
<h1 className="title">Login</h1>
<form action="">
<div className={(!isValidEmail(email) ? 'has-error' : '') + ' input-holder'}>
<Label htmlFor={'loginEmail'} hidden={email !== null && email.length > 0}>email</Label>
<input type="text" className="input" id="loginEmail" value={email !== null ? email : ''}
onChange={this.emailInputChanged}/>
</div>
<div className={(password !== null && password.length === 0 ? 'has-error' : '') + ' input-holder'}>
<Label htmlFor={'loginPassword'}
hidden={password !== null && password.length > 0}>password</Label>
<input type="password" className="input" id="loginPassword"
value={password !== null ? password : ''}
onChange={this.passwordInputChanged}/>
</div>
<button type="submit" className="btn btn-default" id="loginButton"
onClick={this.loginButtonClicked}>
login
</button>
</form>
<div className="utilities">
<a href={'/signup'} onClick={this.signupButtonClicked}>don't have an account?</a>
<a href={'/forgot-password'} onClick={this.forgotPasswordButtonClicked}>forgot your password?</a>
</div>
</div>
)
}
}
export function isValidEmail(email) {
const expression = /\S+#\S+/;
return expression.test(String(email).toLowerCase());
}
The values of the inputs are stored in the component's state. I have given them initial value of null and update them using setState() in the onChange event.
In the render() method I use the state to colour inputs with invalid values. Currently I am only checking the email value against a simple regex and the password to be at least 1 character in length.
The reason I have set the initial values of the state variables to null so I can check in the layout and the initial style on the input to not be marked as "has-errors". However I need to extend the check to:
this.state.email !== null && this.state.email.length === 0
in order to work, because null has no length property.
Is there a cleaner and "React-ish" way to achieve this:
- initial state of the div holding the inputs has no class has-errors
- less checks when setting the value attribute on the input (because React doesn't accept null as value of the attribute)
Edit:
If the initial value of this.state.email and this.state.password are empty strings, I get has-error applied to the div holding the inputs. In my opinion this is bad UX, because the user hasn't done anything and he is already wrong.
The hidden attribute is used by a custom component I made, which acts like "placeholder" (gets erased if something is typed in the input).
Video below showing how my form looks like when this.state.email and this.state.password are empty strings as well how my <Label> component works:
You could create a validate function which return an errors object to know which fields are in error, and use empty strings as initial values. I don't understand what you are trying to do with the hidden attribute.
Edit: add a touched property in the state, to know which field have been touched.
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
touched: {},
};
}
emailInputChanged = e => {
this.setState({
email: e.target.value.trim(),
touched: {
...this.state.touched,
email: true,
},
});
};
passwordInputChanged = e => {
this.setState({
password: e.target.value.trim(),
touched: {
...this.state.touched,
password: true,
},
});
};
loginButtonClicked = e => {
e.preventDefault();
if (!this.isFormValid()) {
//Perform some API request to validate data
}
};
isFormValid = () => {
const errors = this.validate();
return Object.keys(errors).length === 0;
};
validate = () => {
const errors = {};
const { email, password } = this.state;
if (!isValidEmail(email)) {
errors.email = true;
}
if (password.length === 0) {
errors.password = true;
}
return errors;
};
render() {
const { email, password, touched } = this.state;
const errors = this.validate();
return (
<div id="login">
<h1 className="title">Login</h1>
<form action="">
<div
className={
(errors.email && touched.email ? 'has-error' : '') +
' input-holder'
}
>
<Label htmlFor={'loginEmail'}>email</Label>
<input
type="text"
className="input"
id="loginEmail"
value={email}
onChange={this.emailInputChanged}
/>
</div>
<div
className={
(errors.password && touched.password ? 'has-error' : '') +
' input-holder'
}
>
<Label htmlFor={'loginPassword'}>password</Label>
<input
type="password"
className="input"
id="loginPassword"
value={password}
onChange={this.passwordInputChanged}
/>
</div>
<button
type="submit"
className="btn btn-default"
id="loginButton"
onClick={this.loginButtonClicked}
>
login
</button>
</form>
</div>
);
}
}
export function isValidEmail(email) {
const expression = /\S+#\S+/;
return expression.test(String(email).toLowerCase());
}
I am trying to build a contact form where an if else statement checks the validity of the email address entered, then with a nested if else checks whether the honeypot filed has a value and sends an ajaxj post request to an aws api gateway.
The ajax post runs without problem, but the outer else is always run.
Here the code:
import React from 'react'
import './style.scss'
const $ = require('jquery')
class ContactForm extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
email:'',
subject:'',
message:'',
honeypot:'',
result:'',
alertType:'',
formErrors:{
email:'',
name:'',
message:''
},
isFormValid:false,
emailValid:false,
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const target = event.target
const value = target.value
const name = target.name
this.setState({ [name]: value })
}
handleSubmit(event) {
event.preventDefault();
var URL = "https://someaddress/";
var form =this
var data = {
name: this.cleanInput(this.state.name.trim()),
email: this.cleanInput(this.state.email.trim()),
subject: this.cleanInput(this.state.subject.trim()),
message: this.cleanInput(this.state.message.trim()),
}
this.validateField('email',data.email)
data.message = "Bilgiler şunlar:\nAdı:"+data.name+"\nEmail Adresi: "+data.email+"\nKonu:"+data.subject+"\nMesaj:"+data.message
data.subject = "[Bestpet Web Sitesinden Doldurulan Form] "+data.subject;
data.email = "info#atlaspet.com.tr";
if(this.state.emailValid ===true){
if (this.state.honeypot=== ''){
$.ajax({
type: "POST",
url: URL,
dataType: "json",
contentType: "application/json",
data: JSON.stringify(data),
success: function(){
form.setState({name:'',email:'',message:'',subject:'',result:'Form başarıyla gönderildi.',alertType:'alert alert-success'})
},
error: function () {
// show an error message
form.setState({result: 'Sorunlar oluştu. Formu gönderemedik.',alertType:'alert alert-danger'});
},
});
} else {console.log("Hi there, I guess you are not human baby");}
} else { form.setState({result: 'Lütfen girmiş olduğunuz email adresini kontrol ediniz.',alertType:'alert alert-danger'})}
}
validateField(fieldName, value) {
let fieldValidationErrors = this.state.formErrors;
let emailValid = this.state.emailValid;
;
switch (fieldName) {
case 'email':
emailValid = value.match(/^([\w.%+-]+)#([\w-]+\.)+([\w]{2,})$/i);
fieldValidationErrors.email = emailValid ? true : false;
break;
default:
break;
}
this.setState({
formErrors: fieldValidationErrors,
emailValid: fieldValidationErrors.email
}, this.validateForm);
console.log(this)
}
validateForm() {
this.setState({ isFormValid: this.state.emailValid });
}
cleanInput(input){
var search = [
'<script[^>]*?>.*?</script>', // Strip out javascript
'<[/!]*?[^<>]*?>', // Strip out HTML tags
'<style[^>]*?>.*?</style>', // Strip style tags properly
'<![sS]*?--[ \t\n\r]*>', // Strip multi-line comments
]
var text = input
// console.log(search.length)
//var output = preg_replace($search, '', input);
for (let i = 0; i < search.length; i++) {
text = text.replace(new RegExp(search[i], 'gi'), '')
}
return text
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div>
<div className={"col-md-12 "+this.state.alertType}>{this.state.result!=='' && this.state.result}</div>
<input name="honeypot" type="text" style={{display:"none"}} value={this.state.honeypot} onChange={this.handleChange}/>
</div>
<div className="form-group">
<div className="col-md-6">
<label>
Name:
{this.state.formErrors.name!=='' && <div className="col-md-12 alert alert-danger">'Sizinle iletişim kurabilmemiz için bir isim girmelisiniz'</div>}
<input name="name" type="text" value={this.state.name} className ="form-control required" onChange={this.handleChange} />
</label>
</div>
<div className="col-md-6">
<label>
email
<input type="text" name="email" className="form-control required" value={this.state.email} onChange={this.handleChange}/>
</label>
</div>
</div>
<div className="form-group">
<div className="col-md-12">
<label>
Subject
<input type="text" name="subject" className="form-control required" value={this.state.subject} onChange={this.handleChange}/>
</label>
</div>
</div>
<div className="form-group">
<div className="col-md-12">
<label>
Message
<textarea name="message" rows="6" className="form-control required" value={this.state.message} onChange={this.handleChange}/>
</label>
</div>
</div>
<div className="form-group">
<div className="col-md-12">
<input type="submit" value="Submit" className="btn btn-sm btn-block btn-primary"/>
</div>
</div>
</form>
);
}
}
export default ContactForm
The section of code I have problems with is in handleSubmit function.
Thanks for help in advance and a happy new year to all.
I have moved the validity check to handleChange function and it is now working as intended.
Thanks a lot!