I want to create a guestbook application page in HTML which has 3 fields for the user to input:
Name
Message
I wanna make the client check in JavaScript, so below are my snippets of code which I added in the head of the html page.
For the Name I need to put a condition so only letters can be entered, no numbers, no special characters, no spaces or empty field, so I made this
function Validate()
{
var x=document.forms["guest"]["email"].value;
var y=document.forms["guest"]["name"].value;
var regex=/^[a-zA-Z]+$/;
if( y==null || y=="" || (!y.match(regex)))
{
alert("Please enter your Name! ");
return false;
}
My question is: How can I insert a condition so the name must be bigger than 3 letters?
For the e-mail field I made this:
if(x==null || x=="")
{
alert("Please enter your email address!");
return false;
}
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
else
return true;
}
Here I don`t have any question.
Can you help me with that?
Thanks
You should take a look into the length property.
E.g.:
var y=document.forms["guest"]["name"].value;
if(y.length < 3) {
alert("Not a valid name");
return false;
}
Further informations for the length property on w3schools
An other option is to use the HTML5 minlength attribute:
<label>Username: <input name=u required minlength=3></label>
Further informations for the minlength attribute on W3
You really dont even need javascript for this:
<form action="">
<input type="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" name="email" required title="Valid email required" required>
<br>
<input type="text" pattern="[a-zA-Z]{3,}" name="name" required title="Letters only and at least 4 characters" required>
<br>
<input type="text" pattern=".{10,}" name="message" required title="10 characters minimum" required>
<br>
<button>Submit</button>
</form>
</div>