JavaScript form validation (check for all letters only) - javascript

I'm trying to create one function that will check that a field is not blank, contains only letters and spaces. Validating that the field contains letters and spaces only does not appear to work as anything that's put in the field will return the alert message.
I'm trying to say:
If the name field is NOT letters and spaces then display this alert "...". Else return true.
function validateForm() {
var x = document.forms["newsletterForm"]["name"].value;
if (x==null || x=="") {
alert("Name must not be blank");
return false;
}
else if (x!==/^[A-Za-z ]+$/) {
alert("Name contains invalid characters (letters and spaces only!)")
return false;
}
else {
return true;
}
<form name="newsletterForm" action="#" onsubmit="return validateForm()" method="post">
<label for="name">Name*: </label><br>
<input type="text" name="name" placeholder="Fill in your name"1> <br><br>
<label for="email">E-mail*: </label><br>
<input type="text" name="email" placeholder="Fill in your e-mail address"><br><br>
<label for="comments">Comments (optional): </label> <br>
<textarea rows="5" cols="20" name="comments" placeholder="Leave us a message"></textarea><br>
<input type="submit" value="Submit">
</form>

missing } at end of script and missing ; at else if
and use regex for check only letter and space
function validateForm() {
var regex = new RegExp("^[a-zA-Z ]+$");
var x = document.forms["newsletterForm"]["name"].value;
if (x == null || x == "") {
alert("Name must not be blank");
return false;
} else if (!regex.test(x)) {
alert("Name contains invalid characters (letters and spaces only!)");
return false;
} else {
return true;
}
}
<form name="newsletterForm" action="#" onsubmit="return validateForm()" method="post">
<label for="name">Name*: </label><br>
<input type="text" name="name" placeholder="Fill in your name"> <br><br>
<label for="email">E-mail*: </label><br>
<input type="text" name="email" placeholder="Fill in your e-mail address"><br><br>
<label for="comments">Comments (optional): </label> <br>
<textarea rows="5" cols="20" name="comments" placeholder="Leave us a message"></textarea><br>
<input type="submit" value="Submit">
</form>

Hi You can use regex for that
var regexExp = /^[a-zA-Z\s]*$/;
function validateForm() {
var x = document.forms["newsletterForm"]["name"].value;
alert(x)
if (x==null || x=="") {
alert("Name must not be blank");
return false;
}
else if (!regexExp.test(x)) {
alert("Name contains invalid characters (letters and spaces only!)")
return false;
}
}
<form name="newsletterForm" action="#" onsubmit="return validateForm()" method="post">
<label for="name">Name*: </label><br>
<input type="text" name="name" placeholder="Fill in your name"1> <br><br>
<label for="email">E-mail*: </label><br>
<input type="text" name="email" placeholder="Fill in your e-mail address"><br><br>
<label for="comments">Comments (optional): </label> <br>
<textarea rows="5" cols="20" name="comments" placeholder="Leave us a message"></textarea><br>
<input type="submit" value="Submit">
</form>

I'm thinking that the problem is your use of !==. !== would be looking for an absolute match between x and your regular expression object - that is, is x that regular expression object; not does it match that expression.
What about this:
else if (! /^[A-Za-z ]+$/.test(x))

use typeof
try
if(x == null || typeof x !== 'string')
{
//code here
}
An empty string isn't a valid value to check against.

Related

Regular Expressions, Length check in Javascript

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>
Option 1: You can use text-transform: capitalize CSS property which will automatically do the task of converting a name from john cena to John Cena.
Check the example below in the CSS
Option 2:
I have added a new input called Nick name which uses javascript to do the same task.
I have used keyup handler to capture the all key input event so that we can execute a piece of code which will do the job on capitalizing the name.
The result is simple string manipulation which splits the name with <space-character> and converts the first character to uppercase and joins the same with rest of the string.
document.addEventListener("DOMContentLoaded", function() {
document.querySelector("#NickName").addEventListener("keyup", capitalizeName);
});
function capitalizeName() {
if (!this.value) return;
var aNewName = this.value.split(" ").map(function(name) {
return name.charAt(0).toUpperCase() + name.substring(1);
});
this.value = aNewName.join(" ");
}
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 */
#Name {
text-transform: capitalize;
}
<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="text" id="NickName" name="NickName" placeholder="*Nick 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>
Hint:
The RegExp object has a method test which when given a string argument returns true if there was at least one match in the str or false. MDN Documentation
Used as /regexp/.test(str). You already have code that tests for length. You want to test for the length AND for this regex.
When you want to capitalize the first letter of each word, that is called Title Case. There's an excellent answer here for that part of your question

Validation fails when multiple <form> tags are present in the same HTML document

I have multiple form tags in my html doc and want to validate them. However the validation function won't give any result. Tried
adding name field to the <form> the validation() does not return any result.
When I use validation with only one <form> the result is correct.
here are the two form tags:
<div id="pinfo">
<form>
<fieldset>
<legend>Personal Information</legend>
Name:
<input type="text" name="name" value="Enter name">
<br><br>
Email:
<input type="email" name="eamil" value="Enter email id">
<br><br>
Confirm email id:
<input type="text" name="cemail" value="">
<br><br>
Password:
<input type="password" name="pass" value="">
<br><br>
Confirm password:
<input type="password" name="cpass" value="">
<br><br>
</fieldset>
</form>
</div>
<div id="linfo">
<form>
<fieldset>
<legend>Location and Contact</legend>
Location:
State:
<!more code ahead>
<script>
function validateForm() {
var eid = document.forms["loginform"]["emailid"].value;
if (eid == null || eid == "") {
alert("Email id must be entered.");
return false;
}
var pwd = document.forms["loginform"]["password"].value;
if (pwd == null || pwd == ""){
alert("Please enter the password.");
return false;
}
var p = document.forms["locinfo"]["pno"].value;
if (p == null || p=="") {
alert("Please enter the phone no.");
return false;
}
</script>
Validating Form Fields Using JavaScript in FrontPage
There are some mistakes in your code.
You have not given form name as "loginform" which you are using in validation function.
And second thing you missed is "onsubmit" attribute on form element
Here is working code for you
function validateForm() {
console.log(document.forms["loginform"])
var eid = document.forms["loginform"]["eamil"].value;
if (eid == null || eid == "") {
alert("Email id must be entered.");
return false;
}
var pwd = document.forms["loginform"]["pass"].value;
if (pwd == null || pwd == "") {
alert("Please enter the password.");
return false;
}
/*var p = document.forms["locinfo"]["pno"].value;
if (p == null || p == "") {
alert("Please enter the phone no.");
return false;
}*/
}
<div id="pinfo">
<form method="post" name="loginform" action="/" onsubmit="return validateForm()">
<fieldset>
<legend>Personal Information</legend>
Name:
<input type="text" name="name" value="">
<br><br>
Email:
<input type="email" name="eamil" value="">
<br><br>
Confirm email id:
<input type="text" name="cemail" value="">
<br><br>
Password:
<input type="password" name="pass" value="">
<br><br>
Confirm password:
<input type="password" name="cpass" value="">
<br><br>
<input type="submit" name="submit" />
</fieldset>
</form>
</div>

pass function value to output in innerhtml div

Hi guys Im trying to pass the return value from the validation function to an innerhtml in the html section of the document. For some reason is not working.... Any help appreciated.
function validate(form) {
fail = validateName(form.name.value)
fail += validateEmail(form.email.value)
fail += validateCity(form.city.value)
if (fail == "") return true
else { alert(return document.getElementById('#errors').innerHTML=fail;}); return false}
}
function validateName(field) {
if (field == "") return "No name was entered.\n"
else if (field.length < 3) return "Name must be at least 3 characters.\n"
else if (!/[a-zA-Z ]*$/.test(field)) return "Name can only have alphabetical characters.\n"
return ""
}
function validateEmail(field) {
if (field == "") return "No email was entered.\n"
else if (!((field.indexOf(".") > 0) && (field.indexOf("#") > 0)) || /[^a-zA-Z0-9.#_-]/.test(field)) return "The email address is invalid.\n"
return ""
}
function validateCity(field) {
if (field == "") return "No city was entered.\n"
else if (field.length < 3) return "City must be at least 3 characters.\n"
else if (!/[a-zA-Z ]*$/.test(field)) return "City can only have alphabetical characters.\n"
return ""
}
<form action="<?php echo $editFormAction; ?>" name="subscribe" onSubmit="return validate(this)" id="subscribe" method="POST">
<div id="errors"></div>
<input name="name" autocomplete="off" required pattern="[a-zA-Z ]*$" title="Please enter only alphabetic characters" type="text" id="name" placeholder="Your name"/>
<input name="email" autocomplete="off" required id="email" type="email" title="Please enter your email address" placeholder="Your email address"/>
<input name="city" autocomplete="off" required pattern="[a-zA-Z ]*$" title="Please enter only alphabetic characters" id="city" placeholder="Your city"/>
<section id="buttons">
<input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset">
<input type="submit" name="submit" id="submitbtn" class="submitbtn" tabindex="7" value="Submit this!">
<br style="clear:both;">
</section>
Use errors in place of #errors and remove return from alert like
if (fail == "") return true;
else {
//use innerText in place of innerHTML if #errors is not a div
document.getElementById('errors').innerHTML=fail; use errors in place of #errors
alert(fail);
return false
}
For ethical coding, you might need to avoid returning the value of a function inside the argument of a function or method:
Notice the line:
else { alert(return document.getElementById('#errors').innerHTML=fail;});
The return is passed as part of arguments of the alert().... that seems NOT okay!
This causes Syntax Errors.

Why isn't my instantaneous validation displaying anything?

I have a form that has a number of fields on it. When the user inputs anything, the field should automatically begin sending feedback as to whether or not the input is valid. The javascript code listed is suppose to handle the instantaneous feedback but it gives no reply whatsoever. It is also suppose to stop the form from being submitted if any of the user's input does not match the regular expressions. The regular expressions don't work either but they were working perfectly fine before I used the innerHTML. I would go back to using alerts if using innerHTML wasn't mandatory.
function insert() {
var valid = true;
document.getElementById("MessNM").innerHTML = "";
if (!document.getElementById("name").value.match(/^^[A-Z]{1}[a-z]{3,7}$/)) {
document.getElementById("MessNM").innerHTML = " Please input a proper name.";
valid = false;
}
document.getElementById("MessPS").innerHTML = "";
if (!document.getElementById("password").value.match(/^[a-zA-Z0-9]{4,8}$/)) {
document.getElementById("MessPS").innerHTML = " Please input a proper password with numbers and letters.";
valid = false;
}
document.getElementById("MessPSC").innerHTML = "";
if (document.getElementById("passwordcheck").value != document.getElementById("password").value) {
document.getElementById("MessPSC").innerHTML = " Password does not match.";
valid = false;
}
document.getElementById("MessAD").innerHTML = "";
if (!document.getElementById("address").value.match(/^[a-zA-Z0-9\s,'-]{5,40}$/)) {
document.getElementById("MessAD").innerHTML = " Address is not valid";
valid = false;
}
document.getElementById("MessZC").innerHTML = "";
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}(-[0-9]{4})?$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
} else {
return valid;
}
}
function test() {
var result = true;
if (!insert()) {
result = false;
}
return result;
}
This is the html form that the javascript function is referencing.
<form name="Insert" id="I2" action="order.php" method="post" style="display: none;" onsubmit="return test()">
<p align="left">
<div id="texter">
<input type=text id="name" required="required" onkeyup="insert()" name="name" autocomplete="off" autofocus>Name <span id="MessNM"></span>
<br>
<input type=email id="email" required="required" onkeyup="insert()" name="email">Email Address <span id="MessEM"></span>
<br>
<input type=password id="password" required="required" onkeyup="insert()" name="password">Password <span id="MessPS"></span>
<br>
<input type=password id="passwordcheck" required="required" onkeyup="insert()" name="passwordcheck">Confirm Password <span id="MessPSC"></span>
<br>
<input type=text id="address" required="required" onkeyup="insert()" name="address">Address <span id="MessAD"></span>
<br>
<input type=text id="zipcode" required="required" onkeyup="insert()" name="zipcode">Zipcode <span id="MessZC"></span>
<br>
</div>
<input type="submit" value="submit" onclick="test()">
<input type="reset" value="Clear All">
<br>
<br>
</form>
There are several issues I see.
You have style="display: none;" on the form which makes the whole form invisible.
Your validation function returns false on the first failed validation which means you're only going to show an error message for the first invalid field, e.g. if e-mail address and zip code are invalid you'll only get a message for e-mail address.
The regular expression for the address validation is broken.
When the password confirmation error is fixed the error message doesn't clear.
By the fact that you say it was working when you used alerts, I'm guessing the main issue you're talking about is caused by the fact that each field validation returns false. You probably just had alerts before and returned a boolean at the end of the function. Here's a solution that addresses that issue and the others I mentioned above.
<form name="Insert" id="I2" action="order.php" method="post" onsubmit="return test()">
<p align="left">
<div id="texter">
<input type=text id="name" required="required" onkeyup="insert()" name="name" autocomplete="off"/>Name <span id="MessNM"></span>
<br>
<input type="email" id="email" required="required" onkeyup="insert()" name="email">Email Address <span id="MessEM"></span>
<br>
<input type="password" id="password" required="required" onkeyup="insert()" name="password">Password <span id="MessPS"></span>
<br>
<input type="password" id="passwordcheck" required="required" onkeyup="insert()" name="passwordcheck">Confirm Password <span id="MessPSC"></span>
<br>
<input type="text" id="address" required="required" onkeyup="insert()" name="address">Address <span id="MessAD"></span>
<br>
<input type="text" id="zipcode" required="required" onkeyup="insert()" name="zipcode">Zipcode <span id="MessZC"></span>
<br>
</div>
<input type="submit" value="submit" onclick="test()">
<input type="reset" value="Clear All">
<br>
<br>
</form>
function insert() {
var valid = true;
document.getElementById("MessNM").innerHTML = "";
if (!document.getElementById("name").value.match(/^^[A-Z]{1}[a-z]{3,7}$/)) {
document.getElementById("MessNM").innerHTML = " Please input a proper name.";
valid = false;
}
document.getElementById("MessPS").innerHTML = "";
if (!document.getElementById("password").value.match(/^[a-zA-Z0-9]{4,8}$/)) {
document.getElementById("MessPS").innerHTML = " Please input a proper password with numbers and letters.";
valid = false;
}
document.getElementById("MessPSC").innerHTML = "";
if (document.getElementById("passwordcheck").value != document.getElementById("password").value) {
document.getElementById("MessPSC").innerHTML = " Password does not match.";
valid = false;
}
document.getElementById("MessAD").innerHTML = "";
if (!document.getElementById("address").value.match(/^[a-zA-Z0-9\s,'-]*$/)) {
document.getElementById("MessAD").innerHTML = " Address is not valid";
valid = false;
}
document.getElementById("MessZC").innerHTML = "";
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}(-[0-9]{4})?$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
return valid;
}

Multiple Validation checks - logic error

I am providing a validation feature on a form for passwords. I need to be able to implement a few validation rules and have them all checked on submit. Now to me the code is sound but I think they may be some logic error in my code that I'm too tired to notice (too the coffee machine!)
Here's the JavaScript:
<script type="text/javascript">
<!--
function validate(registerForm)
registerForm.onsubmit=function()
{
var pw1 = document.forms["register"]["password1"].value;
var pw2 = document.forms["register"]["password2"].value;
//Check values are present in both fields
if(pw1 == '' || pw2 == '')
{
alert("Please enter your password twice.");
return false;
}
//Check there no spaces
else if(document.forms["register"]["password1"].value.indexOf(invalid) > - 1)
{
alert("Spaces are not allowed in passwords!");
return false;
}
//Check passwords are the same
else
{
if(pw1 != pw2)
{
alert("The passwords you entered were not the same. Please try again!");
return false;
}
//Accept passwords
{
alert("Password accepted!");
return true;
}
}
}
-->
</script>
And the HTML Form to go with it:
<form id="register">
<label for="username">Username</label>
<input type="text" class="input_text" name="username" id="name" placeholder="e.g. AberLibrary01" />
<br />
<label for="password">Password</label>
<input type="text" class="input_text" name="password1" id="password1" placeholder="e.g. aber01" />
<br />
<label for="re-enterpassword">Re-enter password</label>
<input type="text" class="input_text" name="password2" id="password2" placeholder="e.g. aber01" />
<input type="submit" class="button" value="Register" />
</form>
<script type="text/javascript">
<!--
new validate(document.forms['register']);
-->
</script>
Any ideas of lovely StackOverflow community? The exact problem is that it won't check for spaces in passwords or whether two passwords entered are the same. It successfully checks that there is at least something in both password fields.
Thanks Dan
This line:
else if(document.forms["register"]["password1"].value.indexOf(invalid) > - 1)
invalid is not defined and I suspect this will cause the problems you're facing.
Made changes to your code got it working http://jsbin.com/igonec/edit#preview
ERRORS
Use of var pw1 = document.forms["register"]["password1"]. It was causing errors
Missing else.
Use of invalid instead of " ".
Wrong use of brackets.
I omitted your errors and made the solution more elegant.
Javascipt
function validate()
{
var pw1 = document.getElementById("password1").value;
var pw2 = document.getElementById("password2").value;
//Check values are present in both fields
if(pw1 ==='' || pw2 === '')
{
alert("Please enter your password twice.");
return false;
}
//Check there no spaces
else if(document.getElementById("password1").value.indexOf(" ") > - 1)
{
alert("Spaces are not allowed in passwords!");
return false;
}
//Check passwords are the same
else
{
if(pw1 !== pw2)
{
alert("The passwords you entered were not the same. Please try again!");
return false;
}
else
{
alert("Password accepted!");
return true;
}
}
}
HTML
<form id="register">
<label for="username">Username</label>
<input type="text" class="input_text" name="username" id="name" placeholder="e.g. AberLibrary01" />
<br />
<label for="password">Password</label>
<input type="text" class="input_text" name="password1" id="password1" placeholder="e.g. aber01" />
<br />
<label for="re-enterpassword">Re-enter password</label>
<input type="text" class="input_text" name="password2" id="password2" placeholder="e.g. aber01" />
<input type="submit" class="button" onclick="validate()" value="Register" />
</form>

Categories

Resources