How to validate form input ONLY if input has a value

Guillermo Perez 26 Reputation points
2021-08-07T21:23:47.523+00:00

I have created my model with an e-mail address like this:

[EmailAddress(ErrorMessage = "Please provide a valid E-mail Address.")]
        public string Email { get; set; }

As you can see, this is not marked as Required, my idea is that if somebody is using the form and does not have an email address, is ok... leave that blank... but if you entered something in the box, it should be an e-mail address...

When I run my blazor form, if I don't touch the field it works as expected, in other words, if I leave it blank it works... BUT if I enter a letter it goes into error saying the message I did setup... ok, so if I delete what I did enter and came back to the blank field again, it still says there's an error... in other words, as soon as I enter a single letter into the input box, even if I delete it, it forces to enter an e-mail and it will not move from there unless I provide the e-mail address and that is not what I want, I want that to be optional... please help

How can I tell the form that a blank option is ok, that is not required but if enter something, it should be a valid email? thank for your help...

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,579 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rena Ni - MSFT 2,066 Reputation points
    2021-08-09T02:31:36.657+00:00

    Hi @Guillermo Perez ,

    You could custom EmailAddress attribute like below:

    public class CustomEmailAddress : DataTypeAttribute  
    {  
        public CustomEmailAddress()  
            : base(DataType.EmailAddress)  
        {  
        }      
        public override bool IsValid(object value)  
        {  
            if(value==null || String.IsNullOrEmpty(value.ToString()))  
            {  
                return true;  
            }  
            var flag = new EmailAddressAttribute().IsValid(value.ToString());  
            if (!flag)  
            {  
                return false;  
            }  
            else  
            {  
                return true;  
            }  
        }  
    }  
    

    Model:

    public class ExampleModel  
    {  
        [CustomEmailAddress(ErrorMessage = "Please provide a valid E-mail Address.")]  
        public string Email { get; set; }  
     }  
    

    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,

    Rena

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.