c# - Validation for hh:mm:ss -


i new in c#.net. want validation textbox take hh:mm:ss format. below code , wroking. gives output true 23:45:45 (example only) , true -23:45:45 (example only). want validation return false -23:45:45 (example only) because negative time. running code not work negative time.

          istrue = validatetime(txttime.text);             if (!istrue)             {                  strerrormsg += "\nplease insert valid alpha time in hh:mm:ss formats";                 isvalidate = false;             }    public bool validatetime(string time)     {         try         {             regex regexp = new regex(@"(([0-1][0-9])|([2][0-3])):([0-5][0-9]):([0-5][0-9])");              return regexp.ismatch(time);         }         catch (exception ex)         {              throw ex;         }     } 

i wouldn't use regular expressions @ - i'd try parse result datetime custom format:

public bool validatetime(string time) {     datetime ignored;     return datetime.tryparseexact(time, "hh:mm:ss",                                   cultureinfo.invariantculture,                                    datetimestyles.none,                                   out ignored); } 

(if really want stick regular expressions, follow answer mels. , i'd rid of pointless try/catch block, , construct regex once , reuse it, too.)


Comments