NextJs / Form / Form validation
Form Validation
-
1. Files
1. signup page
src/components/SignUpForm.tsx
import React from "react"; export class SignUp extends React.Component{ } 2 .App.tsx file
import React from 'react'; import './App.css'; import { SignUp } from './components/SignUpForm'; function App() { return ( ); } export default App; 3. signup page
import React from "react"; export class SignUp extends React.Component{ render() { return ( Sign Up
Add functions
import React from "react"; export class SignUp extends React.Component{ handleChange = (event : any) => {} handleSubmit = (event : any) => {} render() { ... ... } } import React from "react"; handleChange = (event : any) => { event.preventDefault(); const { name, value } = event.target; this.setState({[name]: value}); console.log(this.state) ; } handleSubmit = (event : any) => {} export class SignUp extends React.Component{ constructor(props: any) { super(props); this.state = { username : null, email : null, password : null } } render() { ... ... } } Define variables
import React from "react"; interface SignUpProps { name?: any; value?: any; } interface SignUpState { username : string, email : string, password : string, errors : { username : string, email : string, password : string } } handleSubmit = (event : any) => {} export class SignUp extends React.Component { constructor(props: SignUpProps) { super(props); const initialState = { username : '', email : '', password : '', errors : { username : '', email : '', password : '' } } this.state = initialState; this.handleChange = this.handleChange.bind(this); } Validation
handleChange = (event : any) => { event.preventDefault(); const { name, value } = event.target; let errors = this.state.errors; switch (name) { case 'username': errors.username = value.length < 5 ? 'Username must be 5 characters long!': ''; break; case 'email': errors.email = Regex.test(value)? '': 'Email is not valid!'; break; case 'password': errors.password = value.length < 8 ? 'Password must be eight characters long!': ''; break; default: break; } this.setState(Object.assign(this.state, { errors,[name]: value })); console.log(this.state.errors); } error display
render() { const {errors} = this.state return ( Sign Up
Submit function
handleSubmit = (event : any) => { event.preventDefault(); let validity = true; Object.values(this.state.errors).forEach( (val) => val.length > 0 && (validity = false) ); if(validity == true){ console.log("Registering can be done"); }else{ console.log("You cannot be registered!!!") } }