locked
Only alphabets, numbers and Period to be allowed in textbox RRS feed

  • Question

  • User-73514677 posted

    Hi.

    I have 2 asp.net text box in which I want to check that only alphabets, numbers and period character can be used. If any other special character is entered/pasted , it should not be allowed.

    How to achieve this in JavaScript ?

    I have this regex but not sure, how to call it for both the textbox in keypress and how to restrict other special characters

      var regexp1 = new RegExp("^[0-9A-Za-z.]+$");

    Thanks

    Tuesday, February 12, 2019 12:44 PM

Answers

  • User1520731567 posted

    Hi venkatzeus,

    According to your descriptiom,I think you could use the below regex:

    ^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\.]*$

    ?![0-9]+$ : Only numbers are not allowed

    ?![a-zA-Z]+$ : Only alphabets are not allowed

    [0-9A-Za-z\.]* : allow alphabets, numbers and Period

    how to call it for both the textbox in keypress and how to restrict other special characters

    I make a simple demo,you could refer to:

    <input class="Inputtext" type="text" onkeypress="runn()" />
    <span id="regexVaildate" style="color:#C00; display:none"></span>
    
    
        <script>
            function runn() {
                var f1c = $(".Inputtext").val();
                var validator = new RegExp('^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\.]*$');
                var runner = validator.test(f1c);
                if (runner) {
                    $("#regexVaildate").css("display", "inline");
                    $("#regexVaildate").text("right!");
                }
    
                else {
                    $("#regexVaildate").css("display", "inline");
                    $("#regexVaildate").text("wrong!");
                }
            }
        </script>
    

    How it works:

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 13, 2019 6:11 AM