validating 10 characters, can only be numbers, then redirecting to a web address

3.9k Views Asked by At

So what I need to have happen:

User types in 10 digits (only digits) and clicks “Submit” On submit – the user gets redirected to another landing page.

Here is what I’ve done…and its redirecting, but not really validating the 10 characters, or that they are digits. I have another script that does that, but not both together as they use different programming langauges.

<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script>
$(function() {
    $('#myform').submit(function() {
        var myField = $('#myInput').val();
        if (myField == '') {
            alert('10 digit code is required');
            return false;
        }
        // at this stage we know that the form is valid as the user
        // filled the required myField. Now we can redirect
        window.location.href = 'http://www.corel.com';
        return false;
    });
});

</script>

</head>

<body>
<form id="myform" name="form1" method="post" action="">
  <label for="button"></label>
  <label for="myInput"></label>
  <input name="myInput" type="text" id="myInput" value="" size="12" maxlength="10" />
  <input type="submit" name="button" id="button" value="Submit" />
</form>
2

There are 2 best solutions below

2
On

replace your if with

if (isNaN(myField) || myField.length !== 10) {

EDIT: your best bet looks to be

if (/^\d{10}$/.test(someValue)) {

Which is Pointy's answer, so go with that :)

0
On

You can check to see that a string is a 10-character string of digits like this:

if (/^\d{10}$/.test(someValue)) {
  // it is OK
}
else {
  // not OK
}