简体   繁体   中英

How to validate textbox using Javascript Validator?

I have textbox inside the gridview. My requirement is to restrict the input of the textbox into 'X' or 'O' only nothing else. But I am quite new in javascript. Can anyone please tell me how I can achieve that. I would like to mention that I have used Vb.Net and Asp.Net to develop the system. Thanks in advance for your help.

Here's a jQuery solution if you need to use inputs instead of checkboxes:

$(document).ready(function() {
    jQuery('#restricted-input').on('keydown', function(event) {
        // reset input
        var input = jQuery(this).val('');

        // code 88 = x
        // code 79 = o
        // code 8  = Backspace
        if (event.keyCode == 88 || event.keyCode == 79 || event.keyCode == 8) {
            // let input happen                 
        } else {
            event.preventDefault();
        }
    });
});

Hi if you like this solution

        function val(e) {
        tecla = (document.all) ? e.keyCode : e.which;
        if (tecla == 8) return true;
        patron = /[O-Xox]/;
        te = String.fromCharCode(tecla);
        return patron.test(te);
        }

Thank you everyone for your helpful suggestion to my problem. But here is how I have solved it just now.

This is my Textbox inside the gridview:

 <asp:TextBox ID="txtAttend" runat="server" BackColor="Control" MaxLength="1" 
EnableViewState="true" Width="15px" onkeyup="ValidateText(this);"></asp:TextBox>

Here, I am calling the ValidateText(this) javascript function.

And here is the function:

 <script type="text/javascript" language="javascript">
function ValidateText(i) 
{
    if(i.value != "X" || i.value != "O") 
    {
        alert("Please Enter 'X' for Present or 'O' for Absent");
    }
}
</script>

I got the hint for this solution from this link: TextBox inside GridView validation

Thanks.

Please see following code that help you to allow only two characters to input. This code will restrict other key strokes and allow only 'X' and 'O'. For demo please see : http://jsfiddle.net/BhaveshKachhadiya/uNfP2/7/

function validate(evt)
{
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    // alert(charCode);
    if (charCode == 120 || charCode== 88 || charCode==111 || charCode==79 || charCode == 8) {
        return true;
    }
    else
    {
        alert("Please Enter 'X' for Present or 'O' for Absent");
        return false;    
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM