0

I want to validate 2 fields using compare validator 1)Email address (required field - used required field validator) 2)Confirm email address

If I enter abc@abc.com in email address AND abc@abc.com in confirm email address, it will work fine. But when I add space after the email address in one of the textbox, it will say that both emails do not match which is not desirable. How to solve this ? It would be helpful for the user if I would be able to notify to the user that the space is not allowed in email address.

Warrior
  • 139
  • 1
  • 3
  • 10

2 Answers2

2

Well, if a user adds a space the emails do not match so the error message is correct. If you want to add another validation for allowed characters you could use a RegularExpressionValidator on each field. Here's an example with this regex:

<asp:RegularExpressionValidator 
     id="RegValid" 
     ControlToValidate="txtEmail" 
     ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" 
     ErrorMessage="Invalid email address"
     runat="server" >
</asp: RegularExpressionValidator>

Looks like you need more complex validations so you could probably replace everything with a custom validator and test everything. Markup:

<asp:CustomValidator runat="server" OnServerValidate="EmailValidate" Display="Dynamic" ControlToValidate="txtEmail2" ID="vldEmail"></asp:CustomValidator>

Code behind:

protected void EmailValidate(object source, ServerValidateEventArgs args)
{
    if(txtEmail1.Text != txtEmail2.Text) {
        args.IsValid = False
        vldEmail.ErrorMessage = "Emails are different"
    }else {
        //for each condition that fails set IsValid to false and choose the error message:
        args.IsValid = False
        vldEmail.ErrorMessage = "..."
    }
}
Community
  • 1
  • 1
nmat
  • 7,430
  • 6
  • 30
  • 43
  • yes I agree with that, in this case I give "Invalid email address" as the error message, but I want to give "No Space allowed" when the space is entered by the user and for all other case "Invalid Email address". Any solution? – Warrior Apr 24 '13 at 14:48
  • @Warrior You could ad another validator with `ValidationExpression="[^\s]+"` – nmat Apr 24 '13 at 14:53
  • yeah, the trouble I am facing with that is 2 error messages are getting displayed – Warrior Apr 24 '13 at 15:02
  • @Warrior maybe a custom validator is simpler in this case. see my updated anwer – nmat Apr 24 '13 at 15:14
0
regex = '^(?=.*[A-Za-z0-9])[\S]*$'

Source

tried it myself works fine :)

Druid
  • 6,423
  • 4
  • 41
  • 56
DiederikEEn
  • 753
  • 8
  • 17