views:

265

answers:

5

I'm looking to accept values of (6 chars long or nothing).

This is for an update form. If a password is entered, I'd like to force 6 chars long. If not, I want to ignore the field.

Here's a REGEX that gets me the 6 char part, any help on handling empty also?

<asp:RegularExpressionValidator id="rev1" runat="server" SetFocusOnError="True"
ErrorMessage="Password must be 6 characters long" Display="Dynamic"
ControlToValidate="TextBox1" ValidationExpression="^[a-zA-Z0-9]{6}$">
+1  A: 

Possible solution:

^[a-zA-Z0-9]{6}$|^$

Either 6 characters, or empty are allowed, nothing else.

Robert P
+2  A: 
^([a-zA-Z0-9]{6}|)$

you can probably even shorten it to

^(\w{6}|)$

\w means 'word character'

Schtibe
\w will accept underscores (don't know if the OP wants those or not).
CAbbott
+2  A: 

Not sure if i got your question right but RegularExpressionValidator does not validate empty inputs. In other words, if TextBox1 is empty Page.IsValid will be true.

UserControl
+1 - This is correct. If TextBox1 contains no value, validation passes.
Keith
+1 - But it's an option you can set on the control. You can tell the control to still validate empty inputs, but you can also tell it to ignore them.
Joel Coehoorn
Had to draw the same conclusion.. Thanks!
madcolor
A: 

I know this is not exactly the answer you're looking for, but I always look at whether I can put such validations into a CustomValidator with a server-side method OnValidate.

Regexes are fun, and great for puzzlers but there are always people who don't get them and won't understand what you are doing.

Always try to err on the side of readability and ease of understanding, particularly if you foresee that you won't be the one maintaining the solution.

While this may seem overly verbose I find this is the kind of solution with the least grief in the long run.

I would use a CustomValidator like this in the ASP page:

<asp:CustomValidator ID="rev1" runat="server" 
            ValidateEmptyText="true"
            ControlToValidate="TextBox1" 
            SetFocusOnError="True" 
            Display="Dynamic"
            OnServerValidate="validatePasswordField"
            ErrorMessage="Password must be 6 characters long"/>

And in the code-behind I'd put something like this:

private const int EMPTY_PASSWORD_LENGTH = 0;
private const int MIN_PASSWORD_LENGTH = 6;
private const int MAX_PASSWORD_LENGTH = 6;

protected void validatePasswordField(object source, 
                                     ServerValidateEventArgs args) {
    if (source == null) return;

    string candidatePassword = TextBox1.Text;

    args.IsValid = isValidPasswordText(candidatePassword);
}

private bool isValidPasswordText(string candidate) {
    return candidate.Length == EMPTY_PASSWORD_LENGTH
     || (candidate.Length >= MIN_PASSWORD_LENGTH 
      && candidate.Length <= MAX_PASSWORD_LENGTH);
}

Well, actually I'd pull the isValidPasswordText(string) definition out into a business-layer class, but that's more of an architectural decision.

Tomas
I nearly always try to avoid ServerSide validation, but thanks.
madcolor
Why on earth? You have to perform server-side validation in addition to client-side anyway. If you don't do validation server-side you're essentially not validating the inputs. Client-side is just for the convenience of the user.
Tomas
Suere you can double check, however any issues should be caught client-side first.
madcolor
I agree, they should be caught client-side and pointed out to the user. However the user may choose to power through (e.g. by turning off javascript) and submit the non-valid data. You must validate server-side as well as client-side, it is not an optional extra.
Tomas
A: 

I think if you just want to use validation control to validate length and empty string you should user customevalidator.

  protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    string txtpassword = txtboxPassword.Text;
    if (txtpassword == string.Empty || txtpassword.Length == 6)
    {
        args.IsValid = true;
    }
    else
    {
        args.IsValid = false;
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        Response.Redirect("Next.aspx");
    }
}
Neil