HTML Form Validations

In this blog, we will see HTML form validation code in JavaScript.
My another blog on AMP HTML and Angular JS.
Form validation for Alphabet only:

Sometimes you may require allowing the only alphabet in a particular input field. For Eg first name and last name, a field should not allow any other character apart from an alphabet.

        function onlyAlphabets(e, t) {
            try {
                if (window.event) {
                    var charCode = window.event.keyCode;
                }
                else if (e) {
                    var charCode = e.which;
                }
                else { return true; }
                if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
                    return true;
                else
                    return false;
            }
            catch (err) {
                alert(err.Description);
            }
        }

You may trigger this function on keypress, see below line of code:

<input type=”text” id=”txtFname” onkeypress=”return onlyAlphabets(event,this);”/>

Email Validation:


function isValidEmail(email) {
            var reg = /^w+([-+.’]w+)*@w+([-.]w+)*.w+([-.]w+)*/;
            return reg.test(email);
        }
To check or call this function use below line of code:
if (isValidEmail($(“#txtEmail”).Val()) == false) {//If regex does not match then return false
alert(‘Invalid Email ID’);               
return false;
            }
To Allow only numeric character for fields like phone number:

        $(‘#txtPhone’).keydown(function (e) {
            // Allow: backspace, delete, tab, escape, enter and .
            if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
            // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) ||
            // Allow: Ctrl+C
        (e.keyCode == 67 && e.ctrlKey === true) ||
            // Allow: Ctrl+X
        (e.keyCode == 88 && e.ctrlKey === true) ||
            // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
                // let it happen, don’t do anything
                return;
            }
            // Ensure that it is a number and stop the keypress
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
        });
This can be achieved by putting the same id (txtPhone)
<input type=”text” id=”txtPhone” maxlength=”10″/>


 To Allow max length in an input fields:

        $(‘#txtPhone’).keyup(validateMaxLength);
        function validateMaxLength() {
            var text = $(this).val();
            var maxlength = $(this).data(‘maxlength’);
            if (maxlength > 0) {
                $(this).val(text.substr(0, maxlength));
            }
        }
<input type=”text” id=”txtPhone” maxlength=”10″ data-maxlength=”10″/>

Leave a Comment

RSS
YouTube
YouTube
Instagram