1

I am trying to validate email id on keypress.. When the user enters invalid email id it should show a message enter valid email id.. If the user enter email(abc@gmail) it should display message enter correct email.. If the user enters (abc@gmail.com or co.in) it should allow to enter next field There is something wrong in regular expression i have entered.. Email doesnt get validated here is the script

<script type="text/javascript">
 $(function() {
             $("#sEmail").bind("keypress", function (event) {
                if (event.charCode != 0) {
                    var regex = new RegExp("^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
                    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
                    if (!regex.test(key)) {
                      alert("Please enter Only email");
                        event.preventDefault();
                        return false;
                    }
                }
            });
            });
 </script>
  • showing alert message on every keypress is annoying UX. You should validate the email field after user leaves the field[i.e on loose focus]. – Anand Sowmithiran Jan 10 '22 at 05:27
  • 1
    Does this answer your question? [Validate email with a regex in jQuery](https://stackoverflow.com/questions/9572254/validate-email-with-a-regex-in-jquery) – Anand Sowmithiran Jan 10 '22 at 05:32

0 Answers0