0
votes

We know usually the CustomValidator control will check the user's input against some arithmetic validation.

I have a textbox in my web form. The text of it doesn't come from user's input, it comes from the database.

MembershipUser user = Membership.Providers["SqlMembershipProvider"].GetUser(userName);
TextUserName.Text = AntiXss.HtmlEncode(user.UserName);

My goal is to use some kind of validator to check whether it is appropriate. If not then change it in the textbox and validate it again. How to do it?

Thanks.

UPDATE CODE:

    protected void ValidateUser()
    {
        string UserNameCreated = TextUserName.Text;
        Match match = Regex.Match(UserNameCreated, @"^[a-zA-Z0-9]{6,}$",
    RegexOptions.IgnoreCase);
    }

     <td class="style4">
            <asp:TextBox ID="TextUserName" runat="server"></asp:TextBox>
        </td><td><asp:CustomValidator ID="CustomValidatorUser" runat="server" ControlToValidate="TextUserName"
                                ErrorMessage="Minimum of 6 (six) alphanumeric characters." 
                OnServerValidate="ValidateUser" Display="Dynamic"
                                ValidateEmptyText="True" ></asp:CustomValidator></td>
1
Validator's purpose is just to validate user input. You might want to use some kind of RegularExpression. You should validate the input before you store it in the database. - Tim Schmelter
You can do it in this pattern. But my case needs me to check it after its displaying the text. - user1108948
You haven't shown your CustomValidator. What problems do you actually have, what is the question? If you set TextUserName.Text to the current user's UserName and he's able to change it, what's the problem then to provide a Validator that validates that input? - Tim Schmelter
The program never reachs the code for validating the textbox. Code updated. - user1108948

1 Answers

0
votes

Your ServerValidate has the wrong signature.

void ServerValidation(object source, ServerValidateEventArgs args)
{
    args.IsValid = Regex.Match(TextUserName.Text, @"^[a-zA-Z0-9]{6,}$", RegexOptions.IgnoreCase);
}