user1361276
user1361276

Reputation: 99

Form Validation using regular expressions

I’m new to Javascript and I am learning regular expressions and was wondering if anyone could shed some light on a couple of problems I came across.

I’m writing feedback form which requires validation before sending and I wasn’t quite sure how to include spaces for the address.

I have this code so far, which works as long as I don’t include spaces:

function isAlphanumeric(elem, helperMsg){
    var alphaExp = /^[0-9a-zA-Z]+$/;
    if(elem.value.match(alphaExp)){
        return true;
    }else{
        alert(helperMsg);
        elem.focus();
        return false;
    }
}

Can I simply insert \w so the expression includes spaces?

Also, I wanted to do an alert which lets the user know the form submission has been successful. Using this code:

if(isAlphabet(firstname, "Please only enter letters for your name")){
if(isAlphabet(surname, "Please only enter letters for your name")){
if(emailValidator(email, "Please enter a valid email address")){
if(isNumeric(phone, "Please enter a valid telephone number")){
if(isAlphanumeric(address1, "Numbers and letters only for address")){
if(isAlphanumeric(pcode, "Please enter a valid postcode")){
{
return true;

}}}}}}}

return false;

Where is the best place to insert the code? I tried after return true, but it didn't work.

Any tips would be great!

Upvotes: 1

Views: 5045

Answers (1)

Ry-
Ry-

Reputation: 225281

\w does not include spaces, so that won't work. If you just want to allow a literal space character, then insert it:

/^[0-9a-zA-Z ]+$/

If you want to allow all kinds of space characters, use \s:

/^[0-9a-zA-Z\s]+$/

As for placing an alert after return true;, that definitely won't work; return, as the name suggests, returns from the function. Execution of the function ends there. Just put the alert before the return true.

You might also consider using && (logical AND) to make things neater there.

if(isAlphabet(firstname, "Please only enter letters for your name")
&& isAlphabet(surname, "Please only enter letters for your name")
&& emailValidator(email, "Please enter a valid email address")
&& isNumeric(phone, "Please enter a valid telephone number")
&& isAlphanumeric(address1, "Numbers and letters only for address")
&& isAlphanumeric(pcode, "Please enter a valid postcode")) {
{
    alert('Form submission successful.');
    return true;
}

return false;

You might also want to reconsider whether you actually want an alert saying the submission was successful. I generally avoid that - if something is successful, it should be obvious.

Upvotes: 3

Related Questions