0

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

8
  • could you add a Fiddle Commented Mar 20, 2014 at 16:25
  • By no action, do you mean the form doesn't submit, the JavaScript doesn't run, or both? Are there any errors in the console? Commented Mar 20, 2014 at 16:25
  • In my opinion JS doesn't run at all. I don't think I can use console Commented Mar 20, 2014 at 16:27
  • If the JavaScript doesn't work correctly, it means that there is most likely an error in the console. What is the error? Also, what is it not doing that it should be? Is it submitting the form when it shouldn't or not submitting the form when it should? Commented Mar 20, 2014 at 16:28
  • Ok, just discovered the JS console in Chrome. Many thanks! Commented Mar 20, 2014 at 16:31

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It can be even simpler... /^[1-9][0-9]$/... having {1} is pointless
Yes,Thank you, forgot about that.
0

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 !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.