• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

NewOldMax/react-material-ui-form-validator: Simple validator for forms designed ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

NewOldMax/react-material-ui-form-validator

开源软件地址(OpenSource Url):

https://github.com/NewOldMax/react-material-ui-form-validator

开源编程语言(OpenSource Language):

JavaScript 100.0%

开源软件介绍(OpenSource Introduction):

Validation component for material-ui forms

license npm version Build Status

Demo

Installation

npm install react-material-ui-form-validator

Versions

  • 0.x, 1.x - supports material-ui <= 0.x
  • ^2.0.0 - supports material-ui >= 1.x || 3.x || 4.x
  • ^3.0.0 - supports material-ui >= 5.x

Implementation of react-form-validator-core for material-ui

Migration guide

From <2.1.1 to >=2.1.1

Breaking changes was introduced to react-form-validator-core in order to avoid legacy context. If you have custom validator components then you should change render method of your input components to renderValidatorComponent.

Before:

import React from 'react';
import { ValidatorComponent } from 'react-material-ui-form-validator';

class SomeValidator extends ValidatorComponent {
    render() {
        // return your validated component
    }
}

export default SomeValidator;

After:

import React from 'react';
import { ValidatorComponent } from 'react-material-ui-form-validator';

class SomeValidator extends ValidatorComponent {
    renderValidatorComponent() {
        // return your validated component
    }
}

export default SomeValidator;

Info

Supported types:

Some rules can accept extra parameter, example:

<TextValidator
   {...someProps}
   validators={['minNumber:0', 'maxNumber:255', 'matchRegexp:^[0-9]$']}
/>

Example

Usage

You can pass any props of field components, but note that errorText prop will be replaced when validation errors occurred. Your component must provide a theme.

import React from 'react';
import Button from '@mui/material/Button';
import { ValidatorForm, TextValidator} from 'react-material-ui-form-validator';

class MyForm extends React.Component {

    state = {
        email: '',
    }

    handleChange = (event) => {
        const email = event.target.value;
        this.setState({ email });
    }

    handleSubmit = () => {
        // your submit logic
    }

    render() {
        const { email } = this.state;
        return (
            <ValidatorForm
                ref="form"
                onSubmit={this.handleSubmit}
                onError={errors => console.log(errors)}
            >
                <TextValidator
                    label="Email"
                    onChange={this.handleChange}
                    name="email"
                    value={email}
                    validators={['required', 'isEmail']}
                    errorMessages={['this field is required', 'email is not valid']}
                />
                <Button type="submit">Submit</Button>
            </ValidatorForm>
        );
    }
}

You can add your custom rules:

import React from 'react';
import Button from '@mui/material/Button';
import { ValidatorForm, TextValidator} from 'react-material-ui-form-validator';

class ResetPasswordForm extends React.Component {

    state = {
        user: {
            password: '',
            repeatPassword: '',
        },
    };

    componentDidMount() {
        // custom rule will have name 'isPasswordMatch'
        ValidatorForm.addValidationRule('isPasswordMatch', (value) => {
            if (value !== this.state.user.password) {
                return false;
            }
            return true;
        });
    }

    componentWillUnmount() {
        // remove rule when it is not needed
        ValidatorForm.removeValidationRule('isPasswordMatch');
    }

    handleChange = (event) => {
        const { user } = this.state;
        user[event.target.name] = event.target.value;
        this.setState({ user });
    }

    handleSubmit = () => {
        // your submit logic
    }

    render() {
        const { user } = this.state;

        return (
            <ValidatorForm
                onSubmit={this.handleSubmit}
            >
                <TextValidator
                    label="Password"
                    onChange={this.handleChange}
                    name="password"
                    type="password"
                    validators={['required']}
                    errorMessages={['this field is required']}
                    value={user.password}
                />
                <TextValidator
                    label="Repeat password"
                    onChange={this.handleChange}
                    name="repeatPassword"
                    type="password"
                    validators={['isPasswordMatch', 'required']}
                    errorMessages={['password mismatch', 'this field is required']}
                    value={user.repeatPassword}
                />
                <Button type="submit">Submit</Button>
            </ValidatorForm>
        );
    }

Currently material-ui doesn't support error messages for switches, but you can easily add your own:

import React from 'react';
import red from '@mui/material/colors/red';
import Checkbox from '@mui/material/Checkbox';
import { ValidatorComponent } from 'react-material-ui-form-validator';

const red300 = red['500'];

const style = {
    right: 0,
    fontSize: '12px',
    color: red300,
    position: 'absolute',
    marginTop: '-25px',
};

class CheckboxValidatorElement extends ValidatorComponent {

    renderValidatorComponent() {
        const { errorMessages, validators, requiredError, value, ...rest } = this.props;

        return (
            <div>
                <Checkbox
                    {...rest}
                    ref={(r) => { this.input = r; }}
                />
                {this.errorText()}
            </div>
        );
    }

    errorText() {
        const { isValid } = this.state;

        if (isValid) {
            return null;
        }

        return (
            <div style={style}>
                {this.getErrorMessage()}
            </div>
        );
    }
}

export default CheckboxValidatorElement;
    componentDidMount() {
        ValidatorForm.addValidationRule('isTruthy', value => value);
    }
...
    <CheckboxValidatorElement
        ...
        validators=['isTruthy']
        errorMessages=['this field is required']
        checked={value}
        value={value} // <---- you must provide this prop, it will be used only for validation
    />
Advanced usage

Contributing

This component covers all my needs, but feel free to contribute.




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap