Javascript to check validation and change textbox color

你。 提交于 2019-12-14 03:34:29

问题


Check out the code:

<script type="text/javascript">
    function ValidateTextBox(source, args) {
        var is_valid = false;

        //Regex goes here
        var regex = /^[a-z A-Z]+$/;
        var check = regex.test($('tbName').val()); //Checks the tbName value against the regex
        if (check == true) {
            //If input was correct
            is_valid = true;
        }
        else {
            //If input is not correct
            $("tbName").css(("background-color", "#A00000"), ("border-color", "#780000"));
        }
        args.IsValid = is_valid; //Returns validity state
    }
</script>

Im trying to check the input of a textbox so its only character between a and z, and A and Z, but it still returns true even on input like "1245".

Why is this?

Thanks


回答1:


$('tbName') may not be a valid selector.

Did you mean to select a class?

$(.tbName')

What about an element with an id=tbName?

$('#tbName')

Also, why do you need to do this? This will NOT be accessible outside of the function, as it is a local variable passed to the function (via its parameters)

args.IsValid = is_valid;

You can just do a simple return:

function ValidateTextBox() {
    var regex = /^[a-z A-Z]+$/;
    return regex.test($('#tbName').val());
}


来源:https://stackoverflow.com/questions/7919734/javascript-to-check-validation-and-change-textbox-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!