forked from aspnet/AspNetWebStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequestFieldValidatorBase.cs
More file actions
75 lines (63 loc) · 2.87 KB
/
Copy pathRequestFieldValidatorBase.cs
File metadata and controls
75 lines (63 loc) · 2.87 KB
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
72
73
74
75
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Web.Helpers;
using System.Web.Mvc;
using Microsoft.Internal.Web.Utils;
namespace System.Web.WebPages
{
public abstract class RequestFieldValidatorBase : IValidator
{
private readonly string _errorMessage;
private readonly bool _useUnvalidatedValues;
protected RequestFieldValidatorBase(string errorMessage)
: this(errorMessage, useUnvalidatedValues: false)
{
}
protected RequestFieldValidatorBase(string errorMessage, bool useUnvalidatedValues)
{
if (String.IsNullOrEmpty(errorMessage))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "errorMessage");
}
_errorMessage = errorMessage;
_useUnvalidatedValues = useUnvalidatedValues;
}
public virtual ModelClientValidationRule ClientValidationRule
{
get { return null; }
}
/// <summary>
/// Meant for unit tests that causes RequestFieldValidatorBase to basically ignore the unvalidated field requirement.
/// </summary>
internal static bool IgnoreUseUnvalidatedValues { get; set; }
protected abstract bool IsValid(HttpContextBase httpContext, string value);
public virtual ValidationResult Validate(ValidationContext validationContext)
{
var httpContext = GetHttpContext(validationContext);
var field = validationContext.MemberName;
var fieldValue = GetRequestValue(httpContext.Request, field);
if (IsValid(httpContext, fieldValue))
{
return ValidationResult.Success;
}
return new ValidationResult(_errorMessage, memberNames: new[] { field });
}
protected static HttpContextBase GetHttpContext(ValidationContext validationContext)
{
Debug.Assert(validationContext.ObjectInstance is HttpContextBase, "For our validation context, ObjectInstance must be an HttpContextBase instance.");
return (HttpContextBase)validationContext.ObjectInstance;
}
protected string GetRequestValue(HttpRequestBase request, string field)
{
if (IgnoreUseUnvalidatedValues)
{
// Make sure we do not set this when we are hosted since this is only meant for unit test scenarios.
Debug.Assert(HttpContext.Current == null, "This flag should not be set when we are hosted.");
return request.Form[field];
}
return _useUnvalidatedValues ? request.Unvalidated[field] : request.Form[field];
}
}
}