async-validator icon indicating copy to clipboard operation
async-validator copied to clipboard

url validation is passed for values without protocol at the beginning but with www.

Open komarovalexander opened this issue 2 years ago • 2 comments

Hello could you explain why "www.ka-table.com" is a valid url? - it does not have protocol https:// - should it be invalid? https://github.com/yiminghe/async-validator/blob/b9a84a7313e8741703e65bbbf878cfa1bad5734f/src/rule/url.ts#L69

expected: "www.ka-table.com" - invalid "https://www.ka-table.com" - valid

thanks

komarovalexander avatar Sep 28 '23 08:09 komarovalexander

should it not be just:

 const regex = `${protocol}${auth}(?:localhost|${ipv4}|${ipv6}|${host}${domain}${tld})${port}${path}`;

?

komarovalexander avatar Sep 28 '23 10:09 komarovalexander

Based on an idea in #303 I added a custom validator using the browser's URL interface. However this allows URLs of the form http:www.example.com. A good compromise seemed to be to use both:

const descriptor = {
    url: [
        // Test 1
        {
            type: 'url',
            required: true,
        },
        // Test 2
        {
            validator: (_, value) => {
                try {
                    new URL(value)
                    return true
                }
                catch {
                    return false
                }
            }
        }
    ]
}
const validator = new Schema(descriptor);
validator.validate({ url: 'www.example.com' }) // Test1: pass; Test2: fail; Overall: fail
validator.validate({ url: 'http:www.example.com' }) // Test1: fail; Test2: pass; Overall: fail
validator.validate({ url: 'http://www.example.com' }) // Test1: pass; Test2: pass; Overall: pass

URL.canParse would be more concise but it looks a bit new, unless you have a polyfill: https://developer.mozilla.org/en-US/docs/Web/API/URL/canParse_static

sfreytag avatar Mar 25 '24 15:03 sfreytag