我正在使用redux-form包作为我的React Redux表单。我知道如何对其他字段进行验证,例如email,name。
但是,我不知道如何以redux-form验证URL。我应该在URL字段中检查的格式是什么?
const renderField = ({ input, label, type, placeholder, message , meta: { touched, error, warning } }) => (
<Form.Field >
<label className="new-font">{label}</label>
<Input {...input} type={type} className="new-font" placeholder={placeholder} />
{touched && error &&
<div>
<Label
basic
color='red'
pointing
className="new-font"
>
{error}
</Label>
</div>
}
{(input.name === ('desc') || input.name === ('hyperlink')) ?
<Message compact>
{message}
</Message> : <span></span>
}
</Form.Field>
)
function validate(values){
const errors ={};
if(!values.name){
errors.name='Please let me know who I should thank!';
}
if(!values.email){
errors.email='Please enter an email address';
}
if (values.email && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)
) {
errors.email = 'Please enter a valid email address e.g test@gmail.com'
}
if(values.desc && values.desc.length > 50 ){
errors.desc="Key in 50 characters or less";
}
if(!values.hyperlink){
errors.hyperlink="Insert a URL address here to your favourite website!";
}
return errors;
}
答案 0 :(得分:1)
您可以使用验证程序包(https://www.npmjs.com/package/validator),该程序具有对电子邮件,URL,ASCII ....的许多验证,因此您可以导入程序包并以以下形式使用它:
var response = await _elasticClient.SearchAsync<ApplicantsWithDetailsResponse>(
s => s
.Query(q => q
.Bool(p =>
p.Must(queryFilter => queryFilter.MatchAll())
.Filter(f => f.Range(r => r.Field("AvailablePercentage").GreaterThanOrEquals(60)))
.Boost(5)
.Filter(f => f.Range(r => r.Field("AvailablePercentage").GreaterThan(0).LessThan(60)))
.Boost(1.2)
)));
答案 1 :(得分:0)
由于redux表单允许您customize其Field
组件,因此您可以使用纯HTML创建一个输入字段来验证这样的网址:
<input id="my_url" name="my_url" value type="url" placeholder="your website goes here" pattern="https?://.+" required >
答案 2 :(得分:0)
您可以使用以下方法更改验证功能:
function validate(values){
const errors ={};
if(!values.name){
errors.name='Please let me know who I should thank!';
}
if(!values.email){
errors.email='Please enter an email address';
}
if (values.email && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)
) {
errors.email = 'Please enter a valid email address e.g test@gmail.com'
}
if(values.desc && values.desc.length > 50 ){
errors.desc="Key in 50 characters or less";
}
if(!values.hyperlink){
errors.hyperlink="Insert a URL address here to your favourite website!";
}
else if(!isUrlValid(values.hyperlink) ) {
errors.hyperlink="Insert a valid URL";
}
return errors;
}
const isUrlValid = (userInput) => {
var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
if(res == null)
return (false );
else
return (true);
};
答案 3 :(得分:0)
我刚刚发布了我的软件包redux-form-validators的新版本。 它使您可以编写更简单的代码,如下所示:
let validations = {
name: required({ msg: 'Please let me know who I should thank!' }),
email: [required(), email()],
desc: length({ max: 50 }),
hyperlink: url(),
}