amapeli
amapeli

Reputation: 5

Javascript form validation - ONLY the first character must be numeric

I'm stuck on one small part of my form - I'd like to make it so just the first character of the street address field is numeric, the rest can be anything. I have fiddled with using indexOf as well as reg ex.. I get close, but not quite.

Any suggestions would be appreciated!

window.onload=function()
{
    document.forms[0].onsubmit=function()
    {

        for(i = 0; i < this.elements.length; i++)
        {
            //alert required field
            if(this.elements[i].className.indexOf("required") != -1)
            {
                if(this.elements[i].value == "")
                {
                    alert("required field");
                    this.elements[i].focus();
                    return false;
                }   

            } 


            //username requirements
            var userLength = document.getElementById("user")

            if((userLength.value.length < 5) || (userLength.value.length > 10))
            {
            alert("username must be between 5-10 characters");
            return false;
            }


            //email address requirements
            var emailMust = document.getElementById("email")

            if((emailMust.value.indexOf("@") == -1) || (emailMust.value.indexOf(".") == -1))
            {
                    alert("email must contain proper characters");
                    return false;
            }


            //address requirements
            var address = document.getElementById("address")
            var regex = new RegExp('/^[0-9]{1}[a-zA-Z0-9]$/');

            if(address.match(regex))
            { 
                alert("address must begin with a number");
                return false;
            }



            //birth year requirements
            var birthYear = document.getElementById("birth")

            if(isNaN(birthYear.value))
            {
                alert("birth year must be a number");
                return false;
            }


        } 

    } 
} 

here`s my html portion:

<form action="#">

<p><label for="user">Username:</label>*</p>
<p><input type="text" class="required" id="user"></p>

<p><label for="email">Email Address:</label>*</p>
<p><input type="text" class="required" id="email"></p>

<p><label for="address">Street Address:</label></p>
<p><input type="text" id="address"></p>

<p><label for="birth">Year of birth:</label>*</p>
<p><input type="text" class="required" id="birth"></p>

<br>
<input type="submit">
<p><i>* required field</i></p>

Upvotes: 0

Views: 4526

Answers (3)

clentfort
clentfort

Reputation: 2504

You could try converting the first char into it's ordinal value and comparing it to the range of ASCII number literals.

var addressValid = address.value.charCodeAt(0);
addressValid = (addressValid >= 48 && addressValid <= 57)

The value addressValid will be true if the first char is a number (0-9). All simple and without regular expression.

Of course you could do all this by directly accessing address.value.charCodeAt(0) in an if but this is for demonstration purpose, therefore more verbose.

Upvotes: 1

Sharanya Dutta
Sharanya Dutta

Reputation: 4021

Change the following line

var regex = new RegExp('/^[0-9]{1}[a-zA-Z0-9]$/');

to

var regex = new RegExp('^[0-9]');

Since your requirement is that just the first character of the street address field is numeric, the rest can be anything, your regular expression should concern itself with the first character only. If you must specify another character class, it shouldn’t be as narrow as [a-zA-Z0-9]. Remember that a valid address may contain characters like comma, hyphen, space and so on.

Upvotes: 4

linstantnoodles
linstantnoodles

Reputation: 4400

You can also use:

var regex = new RegExp('/^[0-9]{1,}[a-zA-Z0-9]*$/');

Here's how {} works:

a{3}    Exactly 3 of a
a{3,}   3 or more of a
a{3,6}  Between 3 and 6 of a

I'd also point out that your pattern isn't accounting for spaces that come after the number. For example, it would not match 123 Rod Street. I'd also include a space in your set (right before the letter a)

For example:

new RegExp('/^[0-9]{1,}[ a-zA-Z0-9]*$/');

Update::

I'd leave off the forward slashes because since you're passing it as a string it will get escaped automatically!!

new RegExp('^[0-9]{1,}[ a-zA-Z0-9]*$'); 

Upvotes: 1

Related Questions