Search code examples
asp.netvalidationwebformscustomvalidator

How to use Customvalidator to check number


I was trying to use Customvalidator to check value, and make sure that the value should be integer and also it can't be null. At beginning, I use the RequiredValidator and RegularExpressionValidator to achieve that. However, I could not put their errormessage in the same place, so I change my solution to use Customvalidator. But I still can't figure out it.

Here is my code

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
     DateTime dt;

     if (string.IsNullOrEmpty(args.Value))
     {
         CustomValidator1.ErrorMessage = "Can not be empty";
         args.IsValid = false;
     }

     else if (????)
     {
        ...
     }
}

Solution

  • You can use int.TryParse or decimal.TryParse to check if the string is a valid number.

    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
         args.IsValid = !string.IsNullOrEmpty(args.Value);
         if (!args.IsValid)
         {
             CustomValidator1.ErrorMessage = "Can not be empty";
         }
         else
         {
             int number;
             args.IsValid = int.TryParse(args.Value, out number);
             if(!args.IsValid)
             {
                 CustomValidator1.ErrorMessage = "Must be a valid integer";
             }
         }
    }
    

    Note that you also have to set ValidateEmptyText to true(default: false). It's the only validator which doesn't need an additional RequiredFieldValidator.