3

Is there a way to make the [Url] validation optional?

As an example

public class Company 
{
        [Required, StringLength(63, MinimumLength = 2)]
        public string Name { get; set; }

        [Url, StringLength(127)]
        public string Url { get; set; }
}

The above validation works exactly as i intended it to with the exception that the Url property cannot be optional. I don't want the validation to throw an error if it is blank rather I just want it to validate only when a user enters a value.

UPDATE: Taking into consideration the answer below from Hamid Shahid. I just added a condition to work around my issue until something better comes up:

        //Making url validation optional, fix
        if (company.Url == string.Empty) company.Url = null;

1 Answer 1

4

The URLAttribute validation returns true for null value. If the URL property has a value of NULL, it would be considered as a valid value. If you are setting it to an empty string, it would be considered invalid.

The code below show decompiled version of UrlAttribute class

// System.ComponentModel.DataAnnotations.UrlAttribute
[__DynamicallyInvokable]
public override bool IsValid(object value)
{
    if (value == null)
    {
        return true;
    }
    string text = value as string;
    if (UrlAttribute._regex != null)
    {
        return text != null && UrlAttribute._regex.Match(text).Length > 0;
    }
    return text != null && (text.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) || text.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) || text.StartsWith("ftp://", StringComparison.InvariantCultureIgnoreCase));
}
Sign up to request clarification or add additional context in comments.

3 Comments

That is true, is there any way i can make it work for empty string ?
No with out of the box functionality. You can write your own custom class if you like
@DonO if you like, can you please mark it as answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.