Javascript: validate single input? - javascript

I'd like to validate a form step by step via Javascript. For example, I've like that as soon as a user fills an input box and goes to another one, a Javascript function is called. In other words, I've like to create a real-time validation.
HTML:
<form id="form_register" method="post" action="">
<fieldset>
<legend>Register</legend>
<ul>
<li>
<label for="username">Username:</label>
<input type="text" name="username" id="username" maxlength="25" />
</li>
<li>
<label for="password">Email address:</label>
<input type="text" name="email" id="email" maxlength="50"/>
</li>
<li>
<label for="password">Password:</label>
<input type="password" name="password" id="password" maxlength="32"/>
</li>
<li>
<label for="password">Confirm Password:</label>
<input type="password" name="cpassword" id="cpassword" maxlength="32"/>
</li>
</ul>
<input type="submit" value="Create Account">
</legend>
</fieldset>
</form>
I've already created the .js file and it looks like the following one.
Javascript:
function checkUsername(){
//etc..
}
function checkEmail(){
//etc..
}
function checkPassword(){
//etc..
}
function checkConfirmPassword(){
//etc..
}
How do I link the HTML page with the script?
Thank you.

Use the onblur event, as described here
<input type="text" name="username" id="username" maxlength="25" onblur="checkUsername()" />

It sounds like you're looking to execute these functions on the blur event for each input element. Something like this:
var usernameInput = document.getElementById('username');
usernameInput.onblur = checkUsername;

//How do I link the HTML page with the script? Thank you.
using the script tag:
also, i am not sure why everyone is suggesting onblur, isn't onchange is better for validation purpose? why would we want to validate when the value is not changed? onblur may be required only when the validation of a field is dependant on the value of other fields.

You could do this:
$('input').onblur(function() {
if ($(this).is('[name=username]')) checkUsername()
// etc
})

Related

onsubmit form validation. Form submits even though there are errors

I created a registration page, and each field requires entry and validation. I used the onsubmit event to call my js function to validate the form if the field is empty, however it still submits even though it has not been validated properly.
function validate() {
var streetName = document.getElementById("sN").value;
if (streetName == "" || streetName == null || streetName == undefined) {
window.alert("Sorry");
return false;
}
}
<form name="myForms" action="https://httpbin.org/post " method="post" class="form" onsubmit="return validate()">
<div id="fN">
<label>First Name</label>
<input type="text" name="firstName" placeholder="Enter first name" required>
</div>
<br>
<div class="lN">
<label>Last Name</label>
<input type="text" name="lastName" placeholder="Enter last name" required="">
</div>
<br>
<div class="sN">
<label>Street name</label>
<input type="text" name="streetname" placeholder="Enter your street name">
</div>
// Somemore inputs
<input class="buttons" type="submit" name="submit" value="Sign up" onclick="validate()">
</form>
I expect a window to pop up saying "this entry is wrong and for this reason", but it submits anyway
EDIT: I apologize I should've been clearer in my post. I will use required in some of the inputs, however I will eventually need to write js code to ensure a phone number is all digits and password = passwordconfirm and a postal code is an actual postal code. In the JS file I just showed what I basically tried doing.
Several things
You have validate on the submit AND on the form submit
You should NEVER call anything in a form "submit" since it will hide the submit event/method
You need to get the correct field
Give the form an ID and use unobtrusive code like this
window.addEventListener("load", function() {
document.getElementById("myForm").addEventListener("submit", function(e) {
var errors = false;
var streetName = this.streetname.value.trim(); // no more action needed
if (!streetName) errors = true;
// more validations
if (errors) {
window.alert("Sorry");
e.preventDefault();
}
});
});
<form id="myForm" action="https://httpbin.org/post " method="post" class="form">
<div id="fN">
<label>First Name</label>
<input type="text" name="firstName" placeholder="Enter first name" >
</div>
<br>
<div class="lN">
<label>Last Name</label>
<input type="text" name="lastName" placeholder="Enter last name" >
</div>
<br>
<div class="sN">
<label>Street name</label>
<input type="text" name="streetname" placeholder="Enter your street name">
</div>
<input class="buttons" type="submit" name="SubmitButton" value="Sign up">
</form>
var streetName = document.getElementById("sN").value;
There is no element with that id in the document.
There is an element with sN as its class name, but getElementById won't find an element by its class and the value of <div class="sN"> will always be undefined. It is the input that will have a value.

How to get string from html form and store to JSON?

I'm coding a signup website, the layout is finish with html and css but I don't know how to get the user name, email and password from the html code and combine them to create a JSON file to send to the server.
<form action="#">
<div class="form-group">
<label for="username">Username</label>
<input class="form-control" type="text" name="username" id="username" placeholder="biker" required />
</div>
<div class="form-group">
<label for="email">Email</label>
<input class="form-control" type="text" name="email" id="email" placeholder="biker#gmail.com" required />
</div>
<div class="form-group">
<label for="password">Password</label>
<input class="form-control" type="password" name="password" id="password" placeholder="********" required />
</div>
<div class="form-group">
<label for="passwordRepeat">Repeat Password</label>
<input class="form-control" type="password" name="passwordRepeat" id="passwordRepeat" placeholder="********" required />
</div>
<div class="m-t-lg">
<ul class="list-inline">
<li>
<input class="btn btn--form" type="submit" value="Register" id="registerbtn" />
</li>
<li>
<a class="signup__link" href="#">I am already a member</a>
</li>
</ul>
</div>
</form>
I heard using javascript and jquery can do this but I have not learned Javascript yet, so I do all the search but still no luck.
Did you try googling your case?
There are multiple similar treads on Stack Overflow too, e.g. https://stackoverflow.com/a/22195193/6108936
Long story short, if you add id to your form
<form action="#" id="myForm">
then you can simply serialize whole form. This requires includind jQuery though.
<script>
var formData = JSON.stringify($("#myForm").serializeArray());
$.ajax({
type: "POST",
url: "yourRoute",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json"
});
</script>
Side note. As you have signup form there, I strongly suggest adding
<div style="position: absolute; left: -5000px;" aria-hidden="true">
<input type="text" name="subject" autofill="off" tabindex="-1" value="">
</div>
inside your form. Then, before validation (either before posting everything as JSON of already in backend) check if subject has content. If yes, congrats, you can avoid the spamming.
Why it works? Bots do not understand whenever the field is hidden and fills all the fields. Only exception when the spam is submitted by a real person, not a bot.
And, unless you have your project under firewall, trust me, you want to do this or any other bot prevention.

jQuery - Select non-sibling element on click

Basically what I am trying to do is hide the spans initially and show the respective span when I click on an input field and when you leave that input field, that span goes away.
So I have a form that looks something like this (simplified):
<form id="form">
<div id="contact-div-1">
<input type="text" placeholder="First Name" name="FNAME" class="field validation" id="mce-FNAME">
</div>
<span>
Please Enter Your First Name
</span>
<div id="contact-div-2">
<input type="text" placeholder="Last Name" name="LNAME" class="field validation" id="mce-LNAME">
</div>
<span>
Please Enter Your Last Name
</span>
<div id="contact-div-3">
<input type="text" placeholder="E-mail Address" name="EMAIL" class="field validation" id="mce-EMAIL">
</div>
<span>
Please Enter A Valid E-mail Address
</span>
</form>
This is currently the JavaScript code that I have but it is not working properly.
$("#form span").hide();
$("input").focus(function(){
$(this).next('span').fadeIn("slow");
}).blur(function(){
$(this).next('span').fadeOut("slow");
}); //end blur
The <span> elements are siblings with the parent <div> elements of each <input>, so you need to use $(this).parent():
$("input").focus(function(){
$(this).parent().next('span').fadeIn("slow");
}).blur(function(){
$(this).parent().next('span').fadeOut("slow");
});
Example on JSFiddle
Also, to reduce repetition in your code, your "focus" and "blur" handlers can be combined, using .bind() with .fadeToggle():
$("input").bind("focus blur", function() {
$(this).parent().next("span").fadeToggle("slow");
});
Updated JSFiddle
There's nothing next to the input, try
$(this).parent().next('span').fadeIn("slow");
Working Code:
HTML
<form id="form">
<div id="contact-div-1">
<input type="text" placeholder="First Name" name="FNAME" class="field validation" id="mce-FNAME">
<span> Please Enter Your First Name </span>
</div>
<div id="contact-div-2">
<input type="text" placeholder="Last Name" name="LNAME" class="field validation" id="mce-LNAME">
<span> Please Enter Your Last Name </span>
</div>
<div id="contact-div-3">
<input type="text" placeholder="E-mail Address" name="EMAIL" class="field validation" id="mce-EMAIL">
<span> Please Enter A Valid E-mail Address </span>
</div>
</form>
js
$("#form span").hide();
$("input").on('focus', function(){
var s = $(this).siblings('span');
s.fadeIn("slow");
}).blur(function(){
$(this).next('span').fadeOut("slow");
});
Fiddle: Working fiddle
Since your span is sibling of the parent div, instead of the input, you must navigate to the div
$("#form span").hide();
$("input").focus(function(){
$(this).parent().next('span').fadeIn("slow");
}).blur(function(){
$(this).parent().next('span').fadeOut("slow");
}); //end blur
If you have control over the HTML, and both the span and input hold related information, it may also make sense to put them close together (i.e., child of the same div). Your original js code would work, then.
HTML
<form id="form">
<div id="contact-div-1">
<input type="text" placeholder="First Name" name="FNAME" class="field validation" id="mce-FNAME">
<span>
Please Enter Your First Name
</span>
</div>
<div id="contact-div-2">
<input type="text" placeholder="Last Name" name="LNAME" class="field validation" id="mce-LNAME">
<span>
Please Enter Your Last Name
</span>
</div>
<div id="contact-div-3">
<input type="text" placeholder="E-mail Address" name="EMAIL" class="field validation" id="mce-EMAIL">
<span>
Please Enter A Valid E-mail Address
</span>
</div>
</form>
JQuery
$("#form span").hide();
$("input").focus(function(){
$(this).next('span').fadeIn("slow");
}).blur(function(){
$(this).next('span').fadeOut("slow");
});
DEMO
You can give id's to your spans that are a function of say the name attribute of the corresponding input and then refer to them directly that way... this way you are also not as captive to whether or not you change the design where the hierarchy isn't the same etc.
For example:
<span id="span_FNAME">...</span>
Then jquery
$("input").focus(function() {
var s = '#span_'+$(this).attr("name");
$(s).fadeIn("slow")
...

Form submit with javascript and input required

I was trying to submit things using a div, HTML5, JavaScript. If I use a submit button the validator (required attribute in the inputs) works the button doesn't submit info. But if I use a div tag it doesn't validate and send the info. Any way to fix it? Or should I do the whole code to validate the info and stop the submit?
<form action="index.php" method="get" name='myform'>
<ul>
<li class="row">
<label class="labels" for="username">Username</label>
<input type="text" id="txtUser" required>
</li>
<li class="row">
<label class="labels" for="password">Password</label>
<input type="password" id="txtPass" required>
</li>
<li id="row2">
<div class="button">Submit</div>
<input type="submit">
</li>
</ul>
</form>
http://www.dropmocks.com/mCyfGJ
Im using the following code.
Javascript submit:
http://www.javascript-coder.com/javascript-form/javascript-form-submit.phtml
HTML
enter code here
If you are submitting via JS then you need to call the form validation yourself. I don't see any issues in your post that would prevent the submit though (without validation). But here's a working example. Keep in mind that not all browsers support html5 validation.
function submitform() {
// Get first form element
var $form = $('form')[0];
// Check if valid using HTML5 checkValidity() builtin function
if ($form.checkValidity()) {
console.log('valid');
$form.submit();
}
else {
console.log('not valid');
}
return false
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="index.php" method="get" name='myform'>
<ul>
<li class="row">
<label class="labels" for="username">Username</label>
<input type="text" id="txtUser" name="sds" required>
</li>
<li class="row">
<label class="labels" for="password">Password</label>
<input type="password" id="txtPass" required>
</li>
<li id="row2">
<div class="button">Submit</div>
<input type="submit">
</li>
</ul>
</form>
I had a similiar problem and solved it this way.
<input type="submit" id="Guardar" name="Guardar" value="Guardar" onClick="if(this.form.checkValidity()){this.form.submit(); this.disabled=true; this.value='Enviando…';}else{this.form.checkValidity();}">
You can use a function to not handle it on element.

Create elements in JQuery inside other

I know how to create a element whit JQuery, but I don't know how to place that element, exactly where I want.
<form action="/register" enctype="multipart/form-data" method="POST">
<span class="help-block">Username</span>
<input id="checkuser" type="text" name="nuser" placeholder="Username"/>
<span class="help-block">Email</span>
<input id="mail" type="text" name="nmail" placeholder="Your m#il"/>
<span class="help-block">Password</span>
<input type="password" name="npass" placeholder="Your password"/>
<span class="help-block">Avatar</span>
<input type="file" name="navatar" accept="image/*">
<br/>
<input type="submit" value="Submit"/>
</form>
I'm doing AJAX request with JQuery, so, depends of the result of the request, I create, or not an element to the left of the inputs. How I do that?
Thank's advance!
If by left of an input you mean before it then you can use .insertBefore().
$("<span/>", {
text: "My newly created span element"
}).insertBefore("input#checkuser");
Or, also you may use .before().

Categories