Thursday, 14 June 2012

All in one Validation in JavaScript


<script type="text/javascript">
        function Validation(obj1, req, email, Numeric) {
            try {
                var val1 = document.getElementById(obj1).value

                if (req == 1) { // For Required field Validation                   
                    if (val1.trim() == '') {
                        alert("Please enter valid value"); return false
                    }
                    return true;
                }
                if (email == 1) {   // For Email ID Validation
                    var filter1 = /^.+@.+\..{2,3}$/;
                    if (filter1.test(val1) != true) {
                        alert("Email ID is not valid");
                        return false;
                    }
                }
                if (Numeric == 1) {  // for Numeric Only Validation
                    var reg = /^-{0,1}\d*\.{0,1}\d+$/;
                    if (reg.test(val1) != true) {
                        alert("Please enter numeric only");
                        return false
                    }
                }

            }
            catch (e) {
            }
        }    
    </script>

In HTML:
<input type="submit" name="btn" value="Button" onclick="return Validation('txt',1,0,1);" 
          id
="Submit" />

No comments:

Post a Comment