How to validate multiple inputs in a form - javascript

Please take a look at this code, I want to know how to validate all these input elements in this single form using JavaScript.
I know they look the same but i have the names in a separate div. Your corrections and contributions to my form will be very much appreciated.
<form name="myForm">
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="password" name="fname"><br><br>
<input type="submit" value="Submit">
</form>

Yes, You can. Try this to Validate data in Java Script
<form name="myForm" onsubmit="return validateData()">
<input type="text" id="name" name="fname"><br><br>
<input type="text" id="username" name="username"><br><br>
<input type="text" id="email" name="email"><br><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
Then You have to create a javaScript Function to Validate the data as above validateDate(), for this, now your code is
<script>
function validateData() {
var fname = document.getElementById("fname").value;
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
//if name is empty
if(fname == "" || username == "" || email == "" || password == "") {
//SOme Error Code here
alert("Please Fill All the Form Data.");
}
if(username.length < 4 || username.length > 20) {
//SOme Error Code here
alert("username must be less than 20 but more than 4 Characters.");
}
// You can add more filters like password length, and so on by using more if conditions
}
</script>
<body>
<form name="myForm" onsubmit="return validateData()">
<input type="text" id="name" name="fname"><br><br>
<input type="text" id="username" name="username"><br><br>
<input type="text" id="email" name="email"><br><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
That's all. :)

Even though this requires jQuery, it can solve your problem:
To use jQuery Validate you just need to include in your code a version of the jQuery library equal or more recent than 1.7 and a file with the plugin.
See an example:
jQuery('form').validate();
After calling the jQuery.fn.validate method, you can validate your fields using data attributes, that are valid to the HTML5, according to the W3C.
See a example to required field:
<form>
<input type="text" data-required />
</form>
https://plugins.jquery.com/validate/

Related

compare the value of two form email fields

I have created a form requiring email validation. So user must type in their email address twice and if they don't match they won't be able to submit. I did this by simply comparing the values of email fields 1 and 2. If they match "disabled" is removed from the submit button.
All was working perfectly when I had the value set to "Insert your email address and "confirm your email address again". However, so that the user does not have to delete that text, I removed the value and used "placeholder" in the HTML instead.
The problem now is that the moment you type anything it's returning as true. I guess it's seeing the blank values as the same, but it's not picking up on the changes to the value as the user types it in.
Why are the two fields always returning as a match?
<html>
<body>
<form class="theForm">
<p> Subscribe to my mailing list</p>
<input type="text" id="name" class="fields" name="name" placeholder="Name">
<input type="text" id="email1" class="fields" name="email" placeholder="Email Address" >
<input type="text" id="email2" class="fields" placeholder="Confirm Email Address" >
<input name="submit" id="submit" class="fields" type="submit" disabled value="Email Addresses
Do Not Match">
</form>
<script>
function verify (){
console.log(`email1.value: ${email1}: Email2: ${email2}`);
if(document.getElementById("email1").value === document.getElementById("email2").value) {
document.getElementById("submit").removeAttribute("disabled");
document.getElementById("submit").style.backgroundColor = "#004580";
document.getElementById("submit").style.cursor = "pointer";
} else {
document.getElementById("submit").setAttribute("disabled", "disabled");
}
}
$(".fields").on("change paste keyup", verify);
</script>
</body>
</html>
try this
<html>
<body>
<form class="theForm">
<p> Subscribe to my mailing list</p>
<input type="text" id="name" class="fields" name="name" placeholder="Name">
<input type="text" id="email1" class="fields" name="email" placeholder="Email Address" >
<input type="text" id="email2" class="fields" placeholder="Confirm Email Address" >
<input id="submit" type="button" onclick="verify()" value="click">
</form>
<script>
function verify()
{
if(document.getElementById("email1").value === document.getElementById("email2").value) {
alert("matched")
} else {
document.getElementById("submit").setAttribute("disabled", "disabled");
alert("not matched")
}
}
</script>
</body>
</html>
This worked for me:
Change the email inputs to [type='email'].
Add the required attribute to #email1.
Add a check to the validity of #email1 in your conditional.
Reset styles to initial (or what you prefer) if the button is reset back to 'disabled'.
Use 'input' event to get the the values updating on every keystroke, 'change' only fires on 'blur' or when the form is submitted.
It'd end up looking like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<form class="theForm">
<p> Subscribe to my mailing list</p>
<input type="text" id="name" class="fields" name="name" placeholder="Name">
<input type="email" id="email1" class="fields" name="email" placeholder="Email Address" required>
<input type="email" id="email2" class="fields" placeholder="Confirm Email Address" >
<input name="submit" id="submit" class="fields" type="submit" disabled value="Email Addresses Do Not Match">
</form>
<script>
function verify (){
console.log(`email1: ${email1.value}: Email2: ${email2.value}`);
if(document.getElementById("email1").checkValidity() && document.getElementById("email1").value === document.getElementById("email2").value) {
document.getElementById("submit").removeAttribute("disabled");
document.getElementById("submit").style.backgroundColor = "#004580";
document.getElementById("submit").style.cursor = "pointer";
} else {
document.getElementById("submit").setAttribute("disabled", "disabled");
document.getElementById("submit").style.backgroundColor = "initial";
document.getElementById("submit").style.cursor = "initial";
}
}
$(".theForm").on("input paste keyup", "input[type=email]", verify);
</script>
</body>
</html>
MDN Docs for input and change events:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
Instead of:
$(".fields").on("change paste keyup", verify)
Try:
$(".fields").blur(verify)
EDIT:
How about:
$("#email2").blur(verify)
?

Need help javascript

I want to know that in the following code, when I reference an element
by (document.getElementById) and make it equal to a variable for the validation purpose why I can't use the name instead of name1 in javascript.
function validation() {
name1 = document.getElementById('name');
if (name1.value == "") {
alert('this field cannot left empty');
return false;
}
}
<form id="form" action="message.html" method="post" onSubmit='return validation()' />
<input type="text" placeholder="enter your name" id='name' />
<input type="text" placeholder="address" id='address' />
<input type="tel" placeholder="telephone" id="telephone" />
<input type="submit" value="submit">
After adding var to name1 the code will start executing. After adding var you can assign the document.getElementById('name') to name also and it would work. You can run the below snippet for reference.
function validation(){
var name=document.getElementById('name');
if(name.value== ""){
alert('this field cannot left empty');
return false;
}
}
<form id="form" action="message.html" method="post"
onSubmit='return validation()'>
<input type="text" placeholder="enter your name" id='name' />
<input type="text" placeholder="address" id='address' />
<input type="tel" placeholder="telephone" id="telephone" />
<input type="submit" value="submit">
</form>
var name=document.getElementById('name');
You should use var before an element name.
Try using this..
You forgot to declare the variable.
If you are using a variable for assignment you must declare it before using.
For more reference you can look up this popular thread in SO, What is the purpose of the var keyword and when to use it (or omit it)?
function validation(){
var name = document.getElementById('name');
if(name.value== ""){
alert('this field cannot left empty');
return false;
}
}

Check fields contain data and that one is a number

New to javascript but I am trying to check if three fields (1) contain some data and that (2) the third one contains any numbers. The third one is a telephone # field. I realize dashes would be involved. And that the form could validate if a user entered only one number or a number and some text. But I'm starting small. Any help would be great.
function validate(){
if ((document.myForm.fname.value=="") || (document.myForm.lname.value=="")
|| (document.myForm.telenumber.value=="")){
alert("You must fill in all of the required fields!")
return false
}
else
return true
}
<form name="myForm" onsubmit="return validate()">
<label for="fname">First name</label>
<input type="text" id="fname" name="firstname"><BR>
<label for="lname">Last name</label>
<input type="text" id="lname" name="lastname"><BR>
<label for="tele">Telephone number</label>
<input type="text" id="tele" name="telenumber">
<input type='submit' value='Submit' /><br />
</form>
I would use the typeof function to check if fname and lname are strings plus a regular expression to check if the phone number format is valid.
Working code example:
(function(){
function validate(e) {
e.preventDefault();
var fname = document.getElementById('fname').value,
lname = document.getElementById('lname').value,
phone = document.getElementById('tele').value;
//regex example for phone number format
var regex = new RegExp('^((([0-9]{3}))|([0-9]{3}))[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4}$');
//Validation
if(typeof fname === 'string' && typeof lname === 'string' && regex.test(phone))
console.log('Ok. valid user data');
else
alert('Invalid user data!');
}
// Event listner for form submission
document.getElementById('myForm').addEventListener('submit', validate);
})();
<form name="myForm">
<label for="fname">First name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last name</label>
<input type="text" id="lname" name="lastname">
<label for="tele">Telephone number</label>
<input type="text" id="tele" name="telenumber">
<input type='submit' value='Submit' />
</form>
Additional Note:
I'm checking the form controls to be string with typeof for more code clarity, but it is redundant as the form control are always type string.
So if you want the validation condition can be just if(regex.test(phone))

Focus Cursor function JavaScript (code included)

Here is my javascript code for a cursor focus function to go to username if it is blank on a form call "login".
<script type = "text/javascript">
if (document.forms.login.user.value == "")
(
document.forms.login.user.focus();
)
else
(
document.forms.login.password.focus();
)
Do I need to add anything to my form? Here it is.
<form action="form.php" method="post" name="login">
<label for="user"><b>Username:</b></label> <input name="user" type="text" id="user" size="20"/><br/>
<label for="password"><b>Password:</b></label> <input name="password" type="password" id="password" size="20"/><br/>
<input type="hidden" name="action" value="login"/><br/>
<input type="submit" id="submit" value="Login"/>
</form>
This works for me. (Removed the parentheses around the actual if and else sections.)
if (document.forms.login.user.value == "")
document.forms.login.user.focus();
else
document.forms.login.password.focus();
Working Example
http://jsfiddle.net/S8bRL/

How can I have a form where the text in the input disappears when clicked? (for feedburner form)

I've got the following "subscribe by e-mail" form:
<form style="border:1px solid #ccc;padding:3px;text-align:center;" action="http://feedburner.google.com/fb/a/mailverify" method="post" target="popupwindow" onsubmit="window.open('http://feedburner.google.com/fb/a/mailverify?uri=food101coil', 'popupwindow', 'scrollbars=yes,width=550,height=520');return true">
<p>enter e-mail:</p>
<p><input type="text" style="width:140px" name="email"/></p><input type="hidden" value="food101coil" name="uri"/><input type="hidden" name="loc" value="en_US"/><input type="submit" value="SEND" /></form>
I want to move the "enter e-mail" section inside the form part. So that when the user clicks on it, the text will disappear.
Could someone please help me with how to do that?
The following code will do what you want, but also maintain an email once entered..
HTML
<input id="email" type="text" style="width:140px" name="email" value="enter e-mail"/>
JavaScript
<script type="text/javascript">
var emailfield = document.getElementById('email');
emailfield.onfocus = function(){
if (this.value == 'enter e-mail') this.value = '';
}
emailfield.onblur= function(){
if (this.value == '') this.value = 'enter e-mail';
}
</script>
Live example: http://www.jsfiddle.net/YS2Xm/
<input type="text" name="email" onclick="this.value='';" value="enter e-mail" />
Not tested, should work though!

Categories

Resources