Search code examples
jqueryemail-validation

Email validation in js with space in the end


I am using the following code for email validation, taken from jQuery By Example:

function validateEmail(sEmail) {
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (filter.test(sEmail)) {
        return true;
    }
    else {
        return false;
    }
}​

If I put space after entering the valid email then also its giving me invalid email. What can I do for that? Tried a lot but not getting the proper result.


Solution

  • Change

    var sEmail = $('#txtEmail').val();
    

    to

    var sEmail = $.trim($('#txtEmail').val());
    

    this should do the trick