I want to validate my form now, and I wrote some code, it's working perfectly for length constraints but I want to use Regular Expression to filter the values of each element.
I found from a forum, these Regular Expressions:
for Full Name:
var regex = /^[a-zA-Z ]$/;
for Phone:
var regexPhone= /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/;
I guess the HTML5 (input:type email) is enough for email validation
Also I want to do this with the name, that when I type the full name, the first letters change to uppercase letters. For example--> input="john smith", changes to "John Smith".
This is my code:
function validateForm() {
for (var i = 0; i < document.forms[0].elements.length; i++) {
var pedio = document.forms[0].elements[i];
if(pedio.id.indexOf("Name")!=-1){
if (pedio.value.length < 5 || pedio.value.length > 35) {
alert("Full Name must be 5-35 character long");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
}
if ((pedio.id.indexOf("Phone") != -1) && (isNaN(pedio.value))) {
alert("Phone is must contain only numbers");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
if(pedio.id.indexOf("Phone")!=-1){
if (pedio.value.length!=10) {
alert("Phone must be 10 numbers");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
}
}
}
/* No CSS */
<h1 class="Title">Sign Up</h1>
<div>
<form method="post" onsubmit="return validateForm()">
<input type="text" id="Name" name="yourname" placeholder="*Full Name" autocomplete="off" required>
<input type="email" id="Email" name="youremail" placeholder="*E-Mail"autocomplete="off" required>
<input type="tel" id="Phone" name="yourphone" placeholder="*Phone" autocomplete="off" required>
<input type="password" id="Password" name="yourpassword" placeholder="*Password" autocomplete="off" required>
<p class="signup"> The fields with * are required!<br>
-If you have an account, <a class="signup" href="reservation.php">log in</a> now-</p>
<keygen name="security" style="display:none;">
<input type="submit" value="Register">
</form>
</div>