Validation of the e-mail address using JavaScript or JQuery

advertisements

I have to validate E-Mail address using either JS or JQ. Right now I am using JS but unable to pass the value of the text box as the parameter for JS. I want this to be implemented onchange. I found solutions only using a button to validate which i don't want to.

Here is the HTML code.

            <div class="form-group">
                <label class="control-label">Father's E-Mail Address</label>
                <input maxlength="30" pattern=".{1,50}"  onchange="validateEmail(document.getElementById('txtFatherEmail').value);" title="Input Invalid"  type="text" required="required" class="form-control" placeholder="Enter Father's E-Mail Address" id="txtFatherEmail" runat="server"/>
            </div>

Here is the JS I have used.

    function validateEmail(email) {
        var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        var valid = emailReg.test(email);

        if (!valid) {
            alert("False");
        } else {
            alert("True");
        }
    }

Also I would like to know if there's any better way to do this.


If I understand correctly you want to validate input as you type.
To do this you can use onkeyup event.

<div class="form-group">
    <label class="control-label">Father's E-Mail Address</label>
    <input maxlength="30" pattern=".{1,50}"  onkeyup="validateEmail(this.value);" title="Input Invalid"  type="text" required="required" class="form-control" placeholder="Enter Father's E-Mail Address" id="txtFatherEmail" runat="server"/>
</div>