如何在Redux Form中实现URL字段验证?
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://orhttps://— 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 optionalhttp://orhttps://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

