简体   繁体   中英

Using javascript for checking forms

here is my code:

<script>
    function check(){
        var error = '';
        var name = document.forms['form1'].name.value;
        var age = document.forms['form1'].age.value;

        var checkname = new RegExp("^[a-zA-Z]{3,}$");
        var checkage = new RegExp("^[1-9]{1}+[0-9]{1}$");

        if (!checkname.test(name)) error+= 'Blad w nameniu\n';
        if (!checkage.test(age)) error+= 'Blad w ageu\n';

        if (error == '')
            return true;
        else {
            alert(error);
            return false;
        }
    }
</script>
<form name="form1">
    <p>Name: <input type="text" name="name"></p>
    <p>Age: <input type="text" name="age"></p>
    <button type="button" onclick="check()">Send</button>
</form>

I have no idea why the given code simply doesn't work. There is no action at all. I have tried to change <button> to <input type="sumbit"> and <form onSubmit="check()"> but had no luck.

Fiddle

The problem is the regular expression for checkage

var checkage = new RegExp("^[1-9]{1}+[0-9]{1}$");

this needs to be

 var checkage = new RegExp("^[1-9]{1}[0-9]{1}$");

And you can use firebug for firefox ( is a free add-on that helps you a lot).

Have a good day.

The problem of your code is the checkage regular expression. Instead of this :

var checkage = new RegExp("^[1-9]{1}+[0-9]{1}$");

You could try :

var checkage = new RegExp("/(^[1-9]?[0-9]{1}$|^100$)/");

But IMHO, regex is not the good way to validate the age. You should just write a simple function which check if the number is in between 0 - 100 range

Hope this helps !

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