question

GuillermoPerez-9757 avatar image
0 Votes"
GuillermoPerez-9757 asked RenaNi-MSFT answered

How to validate form input ONLY if input has a value

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...

dotnet-aspnet-core-blazor
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

RenaNi-MSFT avatar image
0 Votes"
RenaNi-MSFT answered

Hi @GuillermoPerez-9757 ,

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

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.