how to make a rules by using Ant in a form?

1k views Asked by At

I have a question about rules in a form. Right now it shows the message Please input your Username! and Username must be 26 letters of the alphabet(upper and lowercase) or Arabic number(0-9) or underscore(_) as a character. When I type a space in username, I have already added whitespace: true in the rules, but it will still show both messages, so how could it only show Please input your Username! when I type space at the beginning in username?

import React from 'react';
import { Form, Input, Button } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';

import './login.less';
import logo from './images/logo.png';

const Item = Form.Item; //it must write after Import
const Login = () => {
  const onFinish = values => {
    console.log(values);
  };

  return (
    <div className="login">
      <header className="login-header">
        <img src={logo} alt="logo" />
        <h1>React Project: Backend Admin System</h1>
      </header>
      <section className="login-content">
        <h3>User Login</h3>
        <Form onFinish={onFinish} name="normal_login" className="login-form">
          <Item
            name="username"
            rules={[
              { required: true, whitespace:true, message: 'Please input your Username!' },
              {
                min: 4,
                message: 'username must be at least 4 characters',
              },
              {
                max: 12,
                message: 'username cannot be longer than 12 characters',
              },
              {
                pattern: /^[a-zA-Z0-9_]+$/,
                message:
                  'Username must be 26 letters of the alphabet(upper and lowercase) or Arabic number(0-9) or underscore(_) as a character',
              },
            ]}
          >
            <Input
              prefix={
                <UserOutlined
                  className="site-form-item-icon"
                  style={{ color: 'rgba(0,0,0,.25) ' }}
                />
              }
              placeholder="Username"
            />
          </Item>
          <Item name="password">
            <Input
              prefix={
                <LockOutlined
                  className="site-form-item-icon"
                  style={{ color: 'rgba(0,0,0,.25) ' }}
                />
              }
              type="password"
              placeholder="Password"
            />
          </Item>
          <Item>
            <Button type="primary" htmlType="submit" className="login-form-button">
              Log in
            </Button>
          </Item>
        </Form>
      </section>
    </div>
  );
};
export default Login;
0

There are 0 answers