0

I'm really sorry for this simple question but really my brain doesn't work right now, how can I make validation of my inputs by react?

This is my index.js

import React from 'react';
import './style.scss';

const MyComponent = () => (
    <div style={{margin:'auto', float:'none'}}>

        <table cellSpacing="0" cellPadding="0" style={{margin:'0 auto',marginBottom:'2rem'}}>
            <thead>
            <tr>
                <td>
                    <span
    style={{
        height: '100px',
        width: '100px',
        backgroundColor: 'darkgrey',
        borderRadius: '50%',
        display: 'inline-block'
    }}/>
                </td>
                <td style={{color:'#2c4e88'}}>
                    <h1><p>swedavia</p></h1>
                    <h2><p>swedish airports</p></h2>
                </td>
            </tr>
            </thead>
        </table>


        <form>
            <div style={{color:'darkgrey',padding: '16px'}}>
                <label htmlFor="uname">Username</label>
                <input type="text" name="uname" required/>
                    <label htmlFor="psw">Password</label>
                    <input type="password" name="psw" required/>
                        <div style={{marginTop:'2rem'}}>
                            <button type="submit">ОТПРАВИТЬ</button>
                            <span style={{float: 'right',paddingTop: '16px'}}><a href="#">Forgot password?</a></span>
                        </div>
            </div>
        </form>

    </div>
);
export default MyComponent;

Help me please to create that validation.

I simply need to check if values are not null and to change color of input border to red if values is null!

1

2 Answers 2

4

For this i guess it's better to create React.component to save state of the form into it and upon submit take the state and validate it's values. I recommend you to use some validation library like joi-browser or validator

Something like this

import React from 'react';
import './style.scss';

class MyComponent extends React.Component {
  // initial state
state = {
   username : { val: "", err : "" },
   // ... etc
}

handleInputChange (e)   {
  // your logic for input change
  // you can even including "pre-validation" in this step
  const val = e.target.value;
  this.setState({ username: { val, err: "" } })
}

handleSubmit = () => {
   const { username, password } = this.state
   // better to validate password and login with some library, this is just an example
   // you should reset value of input on error and 
   // add `err`..err should be handled in your template where it should be shown
   if ( !username.length ) this.setState({ username: { val: "", err: "Please fill this field" } })

   //...submit stuff

}

render = () => {
  return ( // your template )
}

}

Hope it helps :)

Sign up to request clarification or add additional context in comments.

Comments

0
import React, { useState } from 'react';
import PropTypes from 'prop-types';

function MyComponent() {
  const initialState = {
    userName: '',
    password: '',
    error: ''
  }

  const [values, setValues] = useState(initialState);

  const handleInputChange = event => {
    const { name, value } = event.target;

    setValues({ ...values, [name]: value.trim() });
  };

  const handleSubmit = event => {
    event.preventDefault();

    if (values.userName.length === 0 || values.password.length === 0) {
      setValues({ ...values, error: "Please fill this field" });
    }
    else {
      setValues({ ...values, error: "" });
    }

    // Handle form submission
    console.log("formData", values);
  };

  return (
    //call handleInputChange on state change event
    //call handleSubmit on onSubmit event
    //display the div containing the error and apply the error class
    <form onSubmit={handleSubmit}>
      {values.error && <div>{values.error}</div>}

      <input type='text' name='userName' placeholder="User Name" value={values.userName || ''} onChange={handleInputChange} />
      <input type='password' name='password' placeholder="Password" value={values.password || ''} onChange={handleInputChange} />
      <button type="submit">Submit</button>
    </form>
  )
}

MyComponent.propTypes = {
  userName: PropTypes.string.isRequired,
  password: PropTypes.string.isRequired,
  error: PropTypes.string.isRequired
};

export default MyComponent;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.