DannyW86
DannyW86

Reputation: 201

How do i add a regex test to my javascript form validation?

I have created a simple form validation using javascript and want to add some pattern tests to the inputs to make sure the correct information is submitted obviously but im very new to this and am looking to see if someone can help me out with regards to adding the pattern tests.

my validation code so far is:

function validate(form) {
var fail = false;
var name = document.getElementById("full_name");

if (name.value.length == 0) {
  document.getElementById("okName").className = "fail";
  fail = true;
}else{
  document.getElementById("okName").className = "success";
}



var email = document.getElementById("email");
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

if (email.value.length == 0) {
  document.getElementById("okEmail").className = "fail";
    fail = true;
}else{
  document.getElementById("okEmail").className = "success";
}

}

I think that I have to add the condition to the "if" statement for the email validation but havn't a clue where to begin? I know how i would do it using jQuery:

if( value.length<1 /*|| value==field_values[$(this).attr('id')]*/ || ( $(this).attr('id')=='email' && !emailPattern.test(value) )  )

but im not sure how to do the same in raw javaScript as I dont know how to target the input for the email in plain javascript! If anyone can help me out it would really be appreciated!

Upvotes: 0

Views: 491

Answers (2)

Kuba Wyrostek
Kuba Wyrostek

Reputation: 6221

This would look like:

var email = document.getElementById("email");
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

if (!emailPattern.test(email.value)) {
  document.getElementById("okEmail").className = "fail";
    fail = true;
}else{
  document.getElementById("okEmail").className = "success";
}

There is no need to check for length of string as well. No need to jQuerize your webpage for such a simple taks. :-)

Some advice:

  • never rely on client-side validation only
  • verify if control actually exists (i.e. if (email) { ... } )
  • trim strings or provide patterns for name as well (your form validates with single space character entered into form field)
  • also your e-mail pattern is not correct actually (dot is "any character" also in [ ])

Upvotes: 2

Andreas Louv
Andreas Louv

Reputation: 47099

if (email.value.length === 0 || !emailPattern.test(email.value) ) {
  document.getElementById("okEmail").className = "fail";
  fail = true;
} else {
  document.getElementById("okEmail").className = "success";
}

Upvotes: 0

Related Questions