Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better to use Validating or Leave event to validate textbox data?

When coding validation logic for a VB .NET textbox, which event handler is better to use: Validating or Leave?

From what I understand, they both occur at the same time. However, according to this article: MSDN: Control.Leave Event, the Leave event occurs right before the validating event. This would initially make me think I would rather use the Leave event, as it occurs first.

However, for code readability, it would make sense to place all validation code in the Validating event.

So, which is the better option, in terms of both efficiency and industry-standards?

like image 309
Taylor K. Avatar asked Nov 15 '12 21:11

Taylor K.


2 Answers

You should always use the Validating event, it was made to support validation. If not to prevent the focus change then at least for the CausesValidation property. Which you set to False on, say, the Cancel button of a dialog. No point in validating anything when the user decides to dismiss the dialog.

like image 160
Hans Passant Avatar answered Nov 13 '22 05:11

Hans Passant


The Validating event is designed for validation. If the text isn't valid, set e.Cancel = True, and focus stays on the text box. Leave is just a notification.

like image 21
prprcupofcoffee Avatar answered Nov 13 '22 04:11

prprcupofcoffee