react值验证消息的材质ui颜色选择器



我正在使用材质ui颜色选择器:https://www.npmjs.com/package/material-ui-color-picker

<ColorPicker
name='color'
defaultValue='#000'
// value={this.state.color} - for controlled component
onChange={color => console.log(color)}

/>

是否有任何价值验证?如果用户输入了错误的值?如何显示错误消息?我找了一下,但什么也找不到。

手动使用颜色检查。定义功能

const isColor = (strColor) => {
const s = new Option().style;
s.color = strColor;
return s.color !== '';
} 

然后在设置值之前进行检查

value={isColor(this.state.color)? this.state.color : '#000000'}

可以检查onChange

onChange={
color => {
if (isColor(color)) {
console.log(color);
} else {
console.error('Invalid Color');
this.setState({color: '#000000'});
}
};
}

我做了自定义验证消息,似乎它正在工作:

colorChanged = (value, type) => {
var isHex = /^#[0-9A-F]{6}$/i.test(value);
if (value && value.length > 0 && !isHex) {
this.setState({ [type]: true });
} else {
this.setState({ [type]: false });
}
};
<Field fullWidth
type="color"
name="textColor"
id="textColor"
label="Text Color"
onChange={(val) => this.colorChanged(val, 'textColor')}
component={FieldWrapper} />
{this.state.textColor && <Typography color="error" className="error-color">Please enter correct Color!</Typography>}

最新更新