首页 > 解决方案 > 如何使用 reactjs 验证我的表单元素?

问题描述

对于这个简单的问题,我真的很抱歉,但我的大脑现在真的不能工作,我怎样才能通过反应来验证我的输入?

这是我的 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;

请帮助我创建该验证。

我只需要检查值是否不为空,如果值为空,则将输入边框的颜色更改为红色!

标签: javascriptreactjsvalidation

解决方案


为此,我想最好创建 React.component 以将表单的状态保存到其中,并在提交时获取状态并验证它的值。我建议您使用一些验证库,例如joi-browser验证器

像这样的东西

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 )
}

}

希望能帮助到你 :)


推荐阅读