Lani Lani - 15 days ago 5
HTML Question

Javascript form validation

I'm trying to make a simple form validation but it doesn't work the way I want it to. What it should do is that the border of the field should turn green/red if it's valid/invalid with the text is correct or incorrect under it.
The E-mail part is the only one which is working the way it should.


<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
</head>
<body>
<script>

function emailcheck(){
var string1=document.example.email.value
if (string1.indexOf("@")==-1){
document.getElementById ("result").innerHTML = "Email nicht korrekt";
document.getElementById ("result").style.color = "#ff0000";
document.getElementById ("emailinput").style.borderColor = "red";
}
else{
document.getElementById ("result").innerHTML = "Email korrekt";
document.getElementById ("result").style.color = "#11aa55";
document.getElementById ("emailinput").style.borderColor = "green";
}
}
function namecheck(){
var string2=document.example.name.value
if /*(something that defines letters?)*/{
document.getElementById ("result2").innerHTML = "Name nicht korrekt";
document.getElementById ("result2").style.color = "#ff0000";
document.getElementById ("nameinput").style.borderColor = "red";
}
else{
document.getElementById ("result2").innerHTML = "Name korrekt";
document.getElementById ("result2").style.color = "#11aa55";
document.getElementById ("nameinput").style.borderColor = "green";
}
}
function telcheck(){
var string3=document.example.tel.value
if /*(something that defines numbers?)*/{
document.getElementById ("result3").innerHTML = "Tel nicht korrekt";
document.getElementById ("result3").style.color = "#ff0000";
document.getElementById ("telinput").style.borderColor = "red";
}
else{
document.getElementById ("result3").innerHTML = "Tel korrekt";
document.getElementById ("result3").style.color = "#11aa55";
document.getElementById ("telinput").style.borderColor = "green";
}
}
</script>
<center>
<form name="example"><input id="emailinput" type="text" style="border:1px solid" size="20" name="email" placeholder="Your Email" onblur="emailcheck()">
<p id="result"></p>
<input id="nameinput" type="text" style="border:1px solid" size="20" name="name" placeholder="Your Name" onblur="namecheck()">
<p id="result2"></p>
<input id="telinput" type="text" style="border:1px solid" size="20" name="tel" placeholder="Please like 123456" onblur="telcheck()">
<p id="result3"></p>
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>

Answer

You have to use regular expressions.

Second if must be something like this

var regex1 = /^[a-zA-Z]*$/; //only letters
var length = string2.length; //if this equals to 0 then user didn't type anything
if(!regex1.test(string2) || length < 1){ ... }

And third like this

var regex2 = /^\d+$/; //only numbers
if(!regex2.test(string3)){ ... }

For more information check here.

Comments