You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Redux Form中实现URL字段验证?

How to Validate URL Fields in redux-form

Hey there! I see you've got a solid start with your redux-form validation for name, email, and description fields. Let's get that URL (hyperlink) validation sorted out for you.

What Format Should a Valid URL Follow?

A standard valid URL should typically include these key components:

  • A protocol (like http:// or https:// — these are essential for most web-facing URLs)
  • A valid domain name (e.g., example.com, my-site.co.uk — can include letters, numbers, hyphens, and dot-separated top-level domains)
  • Optional extras like paths, query parameters, or anchor links (e.g., /blog/post?foo=bar#section)

For basic form validation, we’ll focus on ensuring the URL has a valid protocol and core domain structure.

Updating Your Validation Function

Here’s how to modify your existing validate function to add URL format checks. I’ll use a regex that covers common valid URL patterns, and integrate it right alongside your existing rules:

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!";
  }
  // Add URL format validation here
  if (values.hyperlink && !/^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/i.test(values.hyperlink)) {
    errors.hyperlink = 'Please enter a valid URL (e.g., https://www.example.com)';
  }
  return errors;
}

Quick Regex Breakdown:

  • ^(https?:\/\/)?: Checks for an optional http:// or https:// protocol (remove the ? if you want to force users to include the protocol for stricter validation)
  • ([\da-z.-]+)\.([a-z.]{2,6}): Validates the core domain name (supports multi-part suffixes like .co.uk)
  • ([/\w .-]*)*\/?$: Allows optional paths, query strings, or trailing slashes for flexibility

Testing It Out

With this update, if a user enters something invalid (like example or www.example without the protocol), your form will show the error message prompting them to fix their URL entry.

内容的提问来源于stack exchange,提问作者Seng Wee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:50:30