Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You don't need to use regular expressions, use <code>DateTime.TryParse</code> or <code>DateTime.TryParseExact</code> instead. I recommend using the regular <code>TryParse</code> method because it affords your visitors flexibility in their formats (e.g. some visitors might want to use the 24-hour system, whereas others can use the 12-hour system).</p> <pre><code>String input; DateTime dt; if( !DateTime.TryParse( input, CultureInfo.InvariantCulture /* change if appropriate */, DateTimeStyles.None, out dt ) ) { // show error message } </code></pre> <p>Now as you're using a validator, you'll want to wrap up this logic in a <code>Validator</code> subclass, but it's really easy:</p> <pre><code>public class DateTimeValidator : BaseValidator { protected override bool EvaluateIsValid() { String controlValidationValue = base.GetControlValidationValue(base.ControlToValidate); if( String.IsNullOrEmpty( controlValidationValue ) ) return true; DateTime dt; return DateTime.TryParse( input, CultureInfo.InvariantCulture /* change if appropriate */, DateTimeStyles.None, out dt ); } } </code></pre> <p>Then (assuming you've registered a tag-prefix in <code>web.config</code>) all you need to do is this:</p> <pre><code>&lt;label&gt; Enter a valid date/time value. &lt;input type="text" runat="server" id="someDate" /&gt; &lt;myprefix:DateTimeValidator runat="server" controlToValidate="someDate" /&gt; &lt;/label&gt; </code></pre> <p>You will need a separate <code>&lt;asp:RequiredFieldValidator&gt;</code> if you want the field to be required.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload