-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathURLValidationRule.cs
71 lines (55 loc) · 2.41 KB
/
URLValidationRule.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using CMS.Core;
using Kentico.Community.Portal.Admin;
using Kentico.Xperience.Admin.Base.FormAnnotations;
using Kentico.Xperience.Admin.Base.Forms;
[assembly: RegisterFormValidationRule(
identifier: URLValidationRule.IDENTIFIER,
ruleType: typeof(URLValidationRule),
name: "URL",
description: "Requires a value is a valid URL")]
namespace Kentico.Community.Portal.Admin;
[ValidationRuleAttribute(typeof(URLValidationRuleAttribute))]
public class URLValidationRule : ValidationRule<URLValidationRuleProperties, URLValidationRuleClientProperties, string>
{
public const string IDENTIFIER = "Kentico.Community.Portal.ValidationRule.URL";
public override string ClientRuleName => "@kentico-community/portal-web-admin/URLValidationRule";
protected override string DefaultErrorMessage => "The given value is not a valid URL";
protected override Task ConfigureClientProperties(URLValidationRuleClientProperties clientProperties)
{
clientProperties.RequireHTTPS = Properties.RequireHTTPS;
return base.ConfigureClientProperties(clientProperties);
}
public override Task<ValidationResult> Validate(string value, IFormFieldValueProvider formFieldValueProvider)
{
if (string.IsNullOrWhiteSpace(value))
{
return ValidationResult.SuccessResult();
}
// Validation logic
bool result = Uri.TryCreate(value, UriKind.Absolute, out var uriResult)
&& uriResult.Scheme == Uri.UriSchemeHttps;
if (result)
{
return ValidationResult.SuccessResult();
}
return ValidationResult.FailResult($"{DefaultErrorMessage}: {(result ? uriResult?.ToString() : value)}");
}
}
public class URLValidationRuleProperties : ValidationRuleProperties
{
public override string GetDescriptionText(ILocalizationService localizationService) => "Must be a valid URL";
[CheckBoxComponent(
Label = "Require https",
ExplanationText = "If true the URL must begin with https. True by default."
)]
public bool RequireHTTPS { get; set; } = true;
public override string ErrorMessage { get => base.ErrorMessage; set => base.ErrorMessage = value; }
}
public class URLValidationRuleClientProperties : ValidationRuleClientProperties
{
public bool RequireHTTPS { get; set; }
}
public class URLValidationRuleAttribute : ValidationRuleAttribute
{
public bool RequireHTTPS { get; set; } = true;
}