Reputation: 201
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
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:
Upvotes: 2
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