0

I have a javascript validation function.I need to check if required fileds are empty or wrong mail address.Required fileds empty is working But when i type mail like abc@abc or something wrong then it doent catch the error in my code.

When i type all required fileds but wrong email address ( abc@abc or abc.com like doesn't capture.)

My Code

 function newsValidation() {

    var status = true;
    if (($.trim($('#txtNewsname').val()) == '') || ($.trim($('#txtnewsarea').val()) == '') ||
        ($.trim($('#txtemail').val()) == '')) {

        $("#reqfield").removeClass("hidden");

        if (!ValidateEmail($("#txtemail").val())) {
            $("#emailval").removeClass("hidden");
        }
        status = false;
    }

Email Validate Function

 function ValidateEmail(email) {
    var expr = /^([\w-\.]+)@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    return expr.test(email);
}
TechGuy
  • 4,298
  • 15
  • 56
  • 87

1 Answers1

1

Your test for a valid email is inside the if block which test if the value is not null, so when you enter any value in the text box (whether its valid or not) the if (!ValidateEmail($("#txtemail").val())) { will never be called. Change your script to

function newsValidation() {
  var status = true;
  if (($.trim($('#txtNewsname').val()) == '') || ($.trim($('#txtnewsarea').val()) == '') || ($.trim($('#txtemail').val()) == '')) {
    $("#reqfield").removeClass("hidden");
    status = false;
  } else if (!ValidateEmail($("#txtemail").val())) {
    $("#emailval").removeClass("hidden");
    status = false;
  }
}

Side note: All this functionality is provide out of the box in MVC by simply adding the [Required] and [EmailAddress] attribute to your property and including the relevant scripts (jquery.validate.js and jquery.validate.unobtrusive.js) and @Html.ValidationMessageFor() helpers which means you get both client and server side validation (and it's all done correctly!)