HTML Form - Form keeps validating everything at once - javascript

I'm having validation problems with a HTML form I created. It seems to be running all the validation checks when I validate the first input without entering anything into the second input. I want it so when I finish entering the first input, it validates only that one. Then I can repeat the same process to the second input. Once both inputs are correctly validated then the user can submit.
I've recreated what I have in a JSFiddle which can be found here: http://jsfiddle.net/aJ2Tw/220/. Any help would be appreciated!
Code:
<form action="" method="post" onsubmit="return FormValidation();" onchange="return FormValidation();">
<div class="input-wrapper">
<input type="text" placeholder="First Name" id="firstname" name="name"/>
<input type="text" placeholder="First Name" id="lastName" name="name"/>
</div>
Submit
<script>
function FormValidation(){
//First Name Validation
var fn=document.getElementById('firstname').value;
if(fn == ""){
alert('Please Enter First Name');
document.getElementById('firstname').style.borderColor = "red";
return false;
}else{
document.getElementById('firstname').style.borderColor = "green";
}
if (/^[0-9]+$/.test(document.getElementById("firstname").value)) {
alert("First Name Contains Numbers!");
document.getElementById('firstname').style.borderColor = "red";
return false;
}else{
document.getElementById('firstname').style.borderColor = "green";
}
if(fn.length <=2){
alert('Your Name is To Short');
document.getElementById('firstname').style.borderColor = "red";
return false;
}else{
document.getElementById('firstname').style.borderColor = "green";
}
}
</script>

You can create create flags which will keep track of if a input field has been touched/changed once. Then in your FormValidation method you can only validate/display error only for the fields which have been touched/changed.
<form action="" method="post" onsubmit="return FormValidation();" onchange="return FormValidation();">
<div class="input-wrapper">
<input type="text" onchange="input1Changed()" placeholder="First Name" id="firstname" name="name"/>
<input type="text" onchange="input2Changed()" placeholder="First Name" id="lastName" name="name"/>
</div>
Submit
<script>
function FormValidation(){
if(isInput1Changed)
{
//validations/errors of Firstname
}
if(isInput2Changed)
{
//validations/errors of lastname
}
}
var isInput1Changed = false;
var isInput2Changed = false;
function input1Changed(){
isInput1Changed = true;
}
function input2Changed(){
isInput2Changed = true;
}
</script>
Hope you get the point!

Related

How to determine whether a form is valid and display a popup window depdnding on whether is is valid or not?

I'm trying to create a form where the user fills out their details, the form currently doesn't send if one of the fields has no input in it because I have added in a "required" into each of the tags to create the field. I have written some JavaScript to open a popup if the form is valid but it isn't working, the form submits to my PHP database but the pop up window doesn't appear. Any thoughts? Here is my current JavaScript.
Code for the form fields -
label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..." required>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..." required>
<label for="phonenumber">Phone Number</label>
<input type="text" id="phonenumber" name="phonenumber" placeholder="The best number to contact you on..." required>
Code to call the script -
<button onclick="myFunction()">Submit</button>
JavaScript validation
<script>
function validateForm() {
var x = document.forms["fname"].value;
var y = document.forms["lname"].value;
var p = document.forms["phonenumber"].value;
if ([x == "", y =="", p ==""]); {
alert("Name must be filled out");
return false;
}
}
function myFunction() {
if (x == "") {
return false;
}
else {
alert("Thank you for making an enquiry, a member of our team will be in contact with you soon.");
}
}
Try Code Below
<script>
function validateForm() {
var x = document.forms["Forms"]["fname"].value;
var y = document.forms["Forms"]["lname"].value;
var p = document.forms["Forms"]["phonenumber"].value;
if (x == "" && y =="" && p ==""); {
alert("Name must be filled out");
return false;
}
else
{
return true ;
}
}
<form name="Forms" onSubmit="return validateForm() "><input type="text" name="fname" /><input type="text" name="lname" /><input type="text" name="phonenumber" /></form>
or you can simply use required in every input

How can i validate and alert if the phone has incorrect input?

The phone number and the email must be valid.
This is a basic popup contact form without the phone number validation. I would like to validate the phone number. I heard about regex but i´m not sure how to implement in the code.
Since i don´t understand javascrip yet i hope you can help me.
<form action="#" method="post" id="form">
<h2>Contact Us</h2><hr/>
<input type="text" name="company" id="company" placeholder="Company"/>
<input type="text" name="name" id="name" placeholder="Name"/>
<input type="text" name="email" id="email" placeholder="Email"/>
<input type="text" name="phone" id="email" placeholder="Phone"/>
<a id="submit" href="javascript: check_empty()">Send</a>
</form>
function check_empty(){
if(document.getElementById('company').value == ""
|| document.getElementById('name').value == ""
||document.getElementById('email').value == ""
||document.getElementById('phone').value == "" ){
alert ("Please, fill the fields!");
}
else {
document.getElementById('form').submit();
}
}
//function to display Popup
function div_show(){
document.getElementById('abc').style.display = "block";
}
//function to check target element
function check(e){
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('abc');
var obj2 = document.getElementById('popup');
checkParent(target)?obj.style.display='none':null;
target==obj2?obj.style.display='block':null;
}
//function to check parent node and return result accordingly
function checkParent(t){
while(t.parentNode){
if(t==document.getElementById('abc'))
{
return false
}
else if(t==document.getElementById('close'))
{
return true
}
t=t.parentNode
}
return true
}

Make form validation via custom attributes

please help me to make validation via input tag's custom attribute (in my case: validation). Help me to change my code that it becomes more dynamic and reusable.
var validation = function validation(){// out of grid - rename js name
//validate first name - only letters
var only_letters = /^[A-Za-z]+$/;// allow only letters
if(firstName.value.length === 0){
document.getElementsByClassName("error")[0].innerHTML="First Name is required";
formIsValid = false;
}
else
if(firstName.value.match(only_letters)){
document.getElementsByClassName("error")[0].innerHTML="";
}
else{
document.getElementsByClassName("error")[0].innerHTML="Only characters allowed";
formIsValid = false;
}
//validate email
var email_letters = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(email.value.length === 0){
document.getElementsByClassName("error")[2].innerHTML="Email is required";
formIsValid = false;
}
else
if(email.value.match(email_letters)){
document.getElementsByClassName("error")[2].innerHTML="";
}
else{
document.getElementsByClassName("error")[2].innerHTML="Incorrect email format";
formIsValid = false;
}
<form id="user_form" method="post">
<p> <input type="text" name="first_name" id="first_name" placeholder="First Name" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
<p><input type="text" name="email" id="email" autocomplete="off" placeholder="Email" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
</form>
Well if you look really carefully, you kinda only have one method in it's essence.
Create a method that gets the element, a regex expression, the response container, and that returns a string.
It would look something like this:
function validateMePls(var field, var regex, var placeholder){
var isValid = "";
/** do all your checks here (length, regex, etc), appending 'isValid', then return it at the end */
};
var isValid = validateMePls(email, email_letters, document.getElementsByClassName("error")[2]);
/** and now you check 'isValid' for something in it, so you know if you have an error or not */
That's basically how an optimized version of your code would look.
Sorry for the 'close to Java' code but I haven't been doing any Javascript lately.
Good luck.
You could utilize placeholder attribute, required attribute, setCustomValidity() set to placeholder at invalid event
var inputs = document.querySelectorAll("input:not([type=submit])");
for (var i = 0; i < inputs.length; i++) {
inputs[i].oninvalid = function(e) {
e.target.setCustomValidity(e.target.placeholder)
}
}
<form id="user_form" method="post">
<label for="first_name">
<input type="text" pattern="[a-zA-Z]+$" name="first_name" id="first_name" placeholder="Input letters a-z A-Z" required />
</label>
<br>
<label for="email">
<input type="email" name="email" id="email" autocomplete="off" placeholder="Valid Email is required" required />
</label>
<br>
<input type="submit" />
</form>

JavaScript Validation Form / Not Working

Absolute newbie here - I'm super passionate about coding and just started with Javascript last week...I cannot seem to get this validation to work! Thanks in advance for all your good advice
-S
<script type="text/javascript">
//Registration Form Validation
function validate(){
var firstName=document.getElementById("name").value;
var maleUser = document.getElementById("maleButton").checked;
if(firstName=="" || firstName==" "){
alert("Please enter your first name: ");
return false;
}
else if(maleUser==false){
alert("Please select your gender: ");
}else{
return true; window.location.href="Search/index.htm";
</script>
<!-- Reg Form needing validation -->
<h1>Registration Form</h1>
<p>
<div class=form_settings>
<form name="RegForm" onsubmit="return(validate());" >
First name: <input type="text" name="first_name" id="name" placeholder="Enter your First name" size="35"/>
<br>
Gender:
<input type="radio" name="male" id="maleButton" value="male"> Male
<br>
</p>
</form>
Please correct your HTML code:
<h1>Registration Form</h1>
<div class="form_settings">
<form name="RegForm" action="search/index.htm">
First name:
<input type="text" name="first_name" id="name" placeholder="Enter your First name" size="35"/>
<br>
Gender:
<input type="radio" name="male" id="maleButton" value="male"> Male
<br>
<input type="submit" value="submit" onclick="return(validate());">
</form>
</div>
Add this updated JavaScript code:
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}
function validate(){
var firstName = document.getElementById("name").value;
var maleUser = document.getElementById("maleButton").checked;
if (trim(firstName) === ''){
alert("Please enter your first name: ");
return false;
}
else if(maleUser == false){
alert("Please select your gender: ");
return false;
}
else{
//window.location.href="Search/index.htm";
return true;
}
}
You can see a complete result here: https://jsfiddle.net/logual/ba5f7tkw/
Don't use window.location.href to submit form. Add an action attribute with url and a submit button to your form.
I ran your code and got
Uncaught SyntaxError: Unexpected end of input
on line 20
you're missing a } after your else
else{
return true; window.location.href="Search/index.htm";
Protip: Run in chrome and type CTRL-SHIFT-J

Custom Error Messages in HTML5 Required Form Fields

I've made a form with required fields and custom error messages/validation, which all display/work correctly, however if the error is corrected, the form still cannot be submitted. This was working before I added the inline oninvalid checks. Not sure what I'm doing wrong.
Code:
<form role="form" method="post" action="contact-form.php">
<input type="text" class="input-field" name="name" id="name" placeholder="Name" required oninvalid="this.setCustomValidity ('Please enter your name.')" />
<input type="email" class="input-field" name="email" id="email" placeholder="Email" required />
<textarea name="message" class="textarea-field" id="message" placeholder="Message" required oninvalid="this.setCustomValidity ('Please enter your message.')"></textarea>
<input type="submit" value="Contact Me" class="btn btn-primary btn-xl" />
</form>
<script>
var email = document.querySelector( "#email" );
function setErrorMessage() {
if ( email.validity.valueMissing ) {
email.setCustomValidity( "Please enter your email address." );
} else if ( email.validity.typeMismatch ) {
email.setCustomValidity( "Please enter a valid email address." );
}
};
setErrorMessage();
email.addEventListener( "change", setErrorMessage );
</script>
JSFiddle: http://jsfiddle.net/44Lrgmjc/
Any help would be greatly appreciated!
Thanks.
I adjusted your javascript and added (key) a validate email function. here is a fiddle
function validate{
function email(){
if(form.email.value == "") {
alert("Please enter your email");
form.email.focus();
return false;
}
// regular expression to match only alphanumeric characters and spaces
var re = /^[\w ]+$/;
// validation fails if the input doesn't match our regular expression
if(!re.test(form.email.value)) {
alert("Invalid email address");
form.email.focus();
return false;
}
// validation was successful
return true;
}
function name(){
If(form.name.value == "") {
alert("Please enter your name");
form.name.focus();
return false;
}
// validation was successful
return true;
}
function msg{
if(form.message.value == "") {
alert("Please enter your message");
form.message.focus();
return false;
}
// validation fails if the input doesn't match our regular expression
if(!re.test(form.message.value)) {
alert("Invalid message content");
form.message.focus();
return false;
}
// validation was successful
return true;}}
</script>
<script>
function validateEmail()
{
var emailID = document.form.email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.form.email.focus() ;
return false;
}
return( true );
}
<form role="form" method="post" action="contact-form.php" onsubmit="return validate(this);">
<input type="text" class="input-field" name="name" id="name" placeholder="Name" required oninvalid="alert ('Please enter your name.')"/>
<input type="email" class="input-field" name="email" id="email" placeholder="Email" required oninvalid="alert ('Please enter a valid email.')"/>
<textarea name="message" class="textarea-field" id="message" placeholder="Message" required oninvalid="alert ('Please enter your message.')" ></textarea>
<input type="submit" value="Contact Me" class="btn btn-primary btn-xl"/>
</form>
Reference

Categories

Resources