javascript loses variable value after a validation function - javascript

i tried few days to make this code working but today i got the idea to ask some help. Here is the problem: when i try to send the value of my input fields to my params variable, i just get nothing, an empty value. However when i remove my validation function,
$(document).input.hasAttribute('required').each(function () {
if ($(this).val() == "") {
alert('Please fill all the fields');
}
});
all the parameters are in my url : ?rpt=123456&etc...etc...
Do you know why i loose my variable value on the way? If yes how to solve this?
Thanks for the help
jQuery(document).ready(function() {
jQuery("#vb_report_date").datepicker({
format: 'dd/mm/yyyy',
autoHide: true
});
jQuery("#vb_verify_button").click(function() {
check_required_inputs(true);
});
});
function check_required_inputs(hasbeenSubmited) {
var params = "";
if (hasbeenSubmited) {
$(document).input.hasAttribute('required').each(function() {
if ($(this).val() == "") {
alert('Please fill all the fields');
}
});
params = "?rpt=" + jQuery("#vb_report_no").val() + "&d=" + jQuery("#vb_report_date").val() + "&pin=" + jQuery("#vb_verif_pin").val();
}
window.location.href = "verify-reports.php" + params;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<form id="requiredform" class="verify-box">
<input type="text" id="vb_report_no" placeholder="Report Number" size="22" data-error="This field is required." class="" required>
<input type="text" id="vb_report_date" placeholder="Date of Issue" size="12" class="hasDatepicker" data-error="This field is required." required>
<input type="text" id="vb_verif_pin" placeholder="Verification PIN" size="22">
<input type="submit" value="Verify" id="vb_verify_button">
</form>
</body>
</html>

To select all required inputs in the document, use $(document).find('input[required]').
Your function should look like:
function check_required_inputs(hasbeenSubmited) {
// do the check only when hasBeenSubmited
if (hasbeenSubmited) {
// assume inputs are filled
var isValid = true;
// check required inputs
$(document).find('input[required]').each(function () {
// input value is missing
if ($(this).val() == "") {
alert('Please fill all the fields');
isValid = false;
}
});
// do the redirect if isValid
if (isValid) {
// make query string
var params = "?rpt=" + $("#vb_report_no").val() + "&d=" + $("#vb_report_date").val() + "&pin=" + $("#vb_verif_pin").val();
// do the redirect
window.location.href = "verify-reports.php" + params;
}
}
}

You can use onsubmit method.
<form id="requiredform" class="verify-box" onsubmit="return getdata()" >
<input type="text" id="vb_report_no" placeholder="Report Number" size="22" data-error="This field is required." class="" required>
<input type="text" id="vb_report_date" placeholder="Date of Issue" size="12" class="hasDatepicker" data-error="This field is required." required>
<input type="text" id="vb_verif_pin" placeholder="Verification PIN" size="22">
<input type="submit" value="Verify" id="vb_verify_button">
</form>
function getdata() {
check_required_inputs(true);
}
Try querySelectorAll with an attribute selector to get all required inputs in the document.
document.getElementById('requiredform').querySelectorAll("[required]")
Now function will be like this,
function check_required_inputs(hasbeenSubmited) {
var params = "";
console.log(hasbeenSubmited)
if (hasbeenSubmited) {
document.getElementById('requiredform').querySelectorAll("[required]").forEach(function (element) {
if ($(element).val() == "") {
alert('Please fill all the fields');
}
});
params = "?rpt=" + jQuery("#vb_report_no").val() + "&d=" + jQuery("#vb_report_date").val() + "&pin=" + jQuery("#vb_verif_pin").val();
}
window.location.href = "verify-reports.php" + params;
}
For more details: how to get value from a form before submit
Check the working snippet here..
function check_required_inputs(hasbeenSubmited) {
var params = "";
console.log(hasbeenSubmited)
if (hasbeenSubmited) {
document.getElementById('requiredform').querySelectorAll("[required]").forEach(function (element) {
if ($(element).val()== "") {
alert('Please fill all the fields');
}
});
params = "?rpt=" + jQuery("#vb_report_no").val() + "&d=" + jQuery("#vb_report_date").val() + "&pin=" + jQuery("#vb_verif_pin").val();
}
console.log(params);
window.location.href = "verify-reports.php" + params;
}
function getdata() {
check_required_inputs(true);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="requiredform" class="verify-box" onsubmit="return getdata()" >
<input type="text" id="vb_report_no" placeholder="Report Number" size="22" data-error="This field is required." class="" required>
<input type="text" id="vb_report_date" placeholder="Date of Issue" size="12" class="hasDatepicker" data-error="This field is required." required>
<input type="text" id="vb_verif_pin" placeholder="Verification PIN" size="22">
<input type="submit" value="Verify" id="vb_verify_button">
</form>

Related

The onsubmit event handler javascript not working

I have a problem. When I clicked the submit button nothing happens, even when I filled out the username and password with numbers (I don't want the username and password contains any number so I did make the condition for it), there is no alert display. I do not know where the problem comes from? Can you guys help me with this
Note: the reset function works fine
function validateInput() {
var firstName = document.forms["sign_up"]["firstName"];
var lastName = document.forms["sign_up"]["lastName"];
var email = document.forms["sign_up"]["email"];
var reg = /^[a-zA-Z]+$/;
if (firstName.value !== '' || lastName.value !== '' || email.value !== '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
// return true;
return false; // for the demo, so it doesn't submit
} else {
if (firstName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in username";
return false;
} else if (lastName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in password";
return false;
}
}
}
}
function reset() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("email").innerHTML = "";
}
<form id="sign_up" onsubmit="return validateInput()">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">Submit</button>
<button type="button" onclick="reset();">Cancel</button>
</form>
Use the Pattern attribute in input for validation like below
<input type="text" id="firstName" value="" pattern="[^0-9]*" title="Numbers are not allowed" placeholder="Enter your first name">
for more references: https://www.w3schools.com/tags/att_input_pattern.asp
And for reset functionality use reset
<input type="reset" value="reset">
It's better than create a special function for it and it saves your number of lines:-)
First, try to avoid to inline event handlers as they are not rec-emended at all. Also to reset form values you can simply use reset() method on the form.
Also, do not use innerHTML just to set the text of your error. You can use textContent instead which is better fit in your example.
You can use addEventListener with submit event to check for validation on your firstname and lastname.
I have fixed your code and its all working as expected.
Live Working Demo:
let form = document.getElementById("sign_up")
var firstName = document.getElementById("firstName")
var lastName = document.getElementById("lastName")
var email = document.getElementById("email")
var reset = document.getElementById("clearValues")
var reg = /^[a-zA-Z]+$/;
form.addEventListener('submit', function(e) {
e.preventDefault()
if (firstName.value != '' || lastName.value != '' || email.value != '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
} else if (!firstName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in username";
} else if (!lastName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in password";
}
}
})
reset.addEventListener('click', function(e) {
document.getElementById("sign_up").reset();
})
input {
display:block;
}
<head>
</head>
<body>
<form id="sign_up" action="#">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">
Submit
</button>
<button type="button" id="clearValues" onclick="reset();">
Cancel
</button>
</form>
</body>
You don't need to return a function in onsubmit event. This should work fine.
<form id="sign_up" onsubmit="validateInput()">
Reference:
https://www.w3schools.com/jsref/event_onsubmit.asp

How to check calculation answer of 2 input fields before submitting form

I have a register form with 2 fields includes random int and a result input field for the answer
there's a Javascript code to check fields are not empty when submitting
I'm trying also to calculate the 2 fields and compare it with the result value
Here's the HTML :
<form method="post" id="contactForm" enctype="multipart/form-data" name="q_sign">
<input type="text" name="q_name" id="senderName"/>
<input type="text" name="q_mail" id="senderEmail" />
<input name="val1" type="text" disabled id="val1" value="php random value1" readonly="readonly" />
<input name="val2" type="text" disabled id="val2" value="php random value2" readonly="readonly" />
<input type="text" name="total" id="total" />
<input type="submit" id="sendMessage" name="sendMessage" value="Register" onClick="return check_data(this.form)" />
Javascript part :
function check_data(form) {
var val1 = (document.q_sign.val1.value);
var val2 = (document.q_sign.val2.value);
if(document.q_sign.q_name.value==''){
alert("please enter your name");
return false;
}else if(document.q_sign.q_mail.value==''){
alert("please enter your email");
return false;
}else if(document.q_sign.total.value!=(val1+val2)){ //Issue is here
alert("wrong answer");
return false;
}else{
return true;
}}
maybe this is your expect below
function check_data(form) {
var val1 = (document.q_sign.val1.value);
var val2 = (document.q_sign.val2.value);
if (document.q_sign.total.value != (eval(val1) + eval(val2))) {
alert("wrong answer");
return false;
} else {
return true;
}
}

javascript form validation issue

for my nic input,the no. of characters should be equal to 14 which i already did and the first character should be equal to the first letter in Lastname. how am i suppose to put this validation.
<form name="form" onsubmit="return formValidation()" action="submit.html">
lastname :<input type="text" name="lastname" id="lastname">
</input><br><br>
<label>NIC Number:</label>
<input type="text" name="NIC" id="NIC" pattern="[0-9]{14}" maxlength="14"></input></br></br>
<input id="submit" type="submit" name="submit" id="submit">
You can add a custom validation: JSFiddle
Code
function validateNIC() {
var nic = document.getElementById("NIC").value;
var lname = document.getElementById("lastName").value;
var valid = true;
if (nic.length != 14) {
console.log("Length must be 14 characters");
} else if (nic[0] != lname[0]) {
console.log("First Character of both input should be same");
}
else{
console.log("Valid")
}
}
<input type="text" id="lastName">
<input type="text" id="NIC" maxlength=14>
<button onclick="validateNIC()">validate</button>
try like this using charAt.
var x = 'some string';//value from first field
var y="s2324343353";//value from nic
if(x.charAt(0) == y.charAt(0)){
alert("first character is same");
}// alerts 's'
I have modified pattern to accept first character as alphanumeric. Then following function should help you validate the first character mismatch validation.
function formValidation() {
var ln = document.getElementById("lastname");
var nic = document.getElementById("NIC");
if (ln.value.substr(0, 1) != nic.value.substr(0, 1)) {
alert("NIC first character not acceptable.");
return false;
} else {
return true;
}
}
<form name="form" onsubmit="return formValidation()" action="submit.html">
lastname :
<input type="text" name="lastname" id="lastname">
</input>
<br>
<br>
<label>NIC Number:</label>
<input type="text" name="NIC" id="NIC" pattern="[a-zA-Z0-9][0-9]{13}" maxlength="14"></input>
</br>
</br>
<input id="submit" type="submit" name="submit" id="submit">
function formValidation() {
var lastname = $('#lastname').val();
var NIC = $('#NIC').val();
if (lastname.charAt(0) != NIC.charAt(0)) {
return false;
}

form validation keep the information

I am trying to keep the information that you have already written even if you have an error in completing the form.Now if you have not written something correctly all the fields are cleaned and you have to start from the beginning.
This is the HTML
<form class="form" method="post" action="" name="registration" onsubmit="return formValidation()" >
<h2>Register now for free!</h2>
<label for="Fname">First name :</label>
<input type="text" name="Fname" id="Fname" placeholder="First Name">
<label for="Lname">Last name :</label>
<input type="text" name="Lname" id="Lname" placeholder="Last Name">
<label for="email">Email :</label>
<input type="text" name="email" id="email" placeholder="example#email.com">
<label for="password">Password :</label>
<input type="password" name="password" id="password" placeholder="******">
<label for="cpassword">Confirm Password :</label>
<input type="password" name="cpassword" id="cpassword" placeholder="******">
<label id="gender">Gender : </label>
<input type="radio" name="sex" value="male"><span>Male</span>
<input type="radio" name="sex" value="female"><span>Female</span><br />
<input type="submit" id="submit" name="submit" value="Register">
</form>
This is the Javascript
function formValidation() {
var fName = document.getElementById("Fname").value;
var lName = document.getElementById("Lname").value;
var email = document.getElementById("email").value;
var pass = document.getElementById("password").value;
var cpass = document.getElementById("cpassword").value;
if (fName_validation(fName, 20, 3)) {
if (lName_validation(lName, 20, 3)) {
if (email_validation(email)) {
if (pass_validation(pass, 20, 6)) {
}
}
}
}
function fName_validation(fName, max, min) {
var check_name = /^[A-Za-z\s ]{2,20}$/;
if (!fName.match(check_name)) {
alert("First name should not be empty / length be between " + max + " to " + min);
fName.focus();
return false;
}
return true;
}
function lName_validation(lName, max, min) {
var check_name = /^[A-Za-z\s ]{2,20}$/;
if (!lName.match(check_name)) {
alert("Last name should not be empty / length be between " + max + " to " + min);
lName.focus();
return ;
}
return true;
}
function email_validation(email) {
var checkk_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if (!email.match(checkk_email)) {
alert("Please enter a valid email!");
email.focus();
return ;
}
return true;
}
function pass_validation(pass, max, min) {
var check_password = /(?=.*\d)(?=.*[a-z]).{6,}/;
if (!pass.match(check_password)) {
alert("Your password should have at least one number,one letter and should be a least 6 characters!");
pass.focus();
return false;
}
if (pass !== cpass) {
alert("Password don't match!");
cpass.focus();
return false;
}
}
alert("Well Done!You successfully registered!");
return true;
}
make sure each validation method should return true or false.
please change two return ; to return false
I would not do this with JavaScript! Because HTML5 does the job for you. Therefore there are the <input> attributes required and pattern.
<input type="text" pattern="[A-Za-z]{2,20}" required="" />
The user should be informed which pattern he can use. And everything is fine.
Example

Simple form skips validation/sending and goings straight to ajax message

I have been following this tutorial to validate a form on a HTML5 template I am working on modifying. Here is the link: http://englishpearls.net/dev/contact.html
As you see, the form goes straight to the ajax message and skips everything else. What am I doing wrong?
HTML
<div id="contact_form">
<form method="post" action="contact-post.html" >
<div class="to">
<input id="name" for="name" type="text" class="text" value="Name" name="userName" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Name';}">
<label class="error" for="name" id="name_error">This field is required.</label>
<input id="email" type="text" class="text" value="Email" name="userEmail" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email';}" style="margin-left: 10px">
<label for="email" class="error" for="email" id="email_error">This field is required.</label>
</div>
<div class="to">
<input id="phone" for="phone" type="text" class="text" value="Phone" name="userPhone" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Phone';}">
<label class="error" for="phone" id="phone_error">This field is required.</label>
<input id="subject" type="text" class="text" value="Subject" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Subject';}" style="margin-left: 10px">
<label class="error" for="subject" id="subject_error">This field is required.</label>
</div>
<div class="text">
<textarea id="message" value="Message:" name="userMsg" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Message';}">Message:</textarea>
<label class="error" for="message" id="message_error">This field is required.</label>
</div>
<div>
<input class="button" type="submit" value="Submit" name="submit" />
</div>
</div>
Jquery EDIT: Updated Script
<script type="text/javascript">
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var phone = $("input#phone").val();
if (phone == "") {
$("label#phone_error").show();
$("input#phone").focus();
return false;
}
var subject = $("input#subject").val();
if (subject == "") {
$("label#subject_error").show();
$("input#subject").focus();
return false;
}
var message = $("input#message").val();
if (message == "") {
$("label#message_error").show();
$("input#message").focus();
return false;
}
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&subject=' + subject + '&message=' + message;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "contact-post.html",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='web/images/check.jpg' />");
});
}
});
return false;
});
});
</script>
Without the validation script, the email sends fine. Thanks!
The way your script is setup right now, the AJAX call will fire immediately, regardless of any input. It needs to be inside of this:
$(".button").click(function () {
}
function, which should have an if statement that will only allow the AJAX to fire if the validation of the form is successful.
Updated:
<div id="contact_form">
<form id="contact-post" method="post" action="contact-post.html" >
<div class="to">
<input id="name" for="name" type="text" class="text" placeholder="Name" name="userName" >
<label class="error" for="name" id="name_error">This field is required.</label>
<input id="email" type="text" class="text" placeholder="Email" name="userEmail" style="margin-left: 10px">
<label for="email" class="error" for="email" id="email_error">This field is required.</label>
</div>
<div class="to">
<input id="phone" for="phone" type="text" class="text" placeholder="Phone" name="userPhone" >
<label class="error" for="phone" id="phone_error">This field is required.</label>
<input id="subject" type="text" class="text" placeholder="Subject"style="margin-left: 10px">
<label class="error" for="subject" id="subject_error">This field is required.</label>
</div>
<div class="text">
<textarea id="message" placeholder="Message:" name="userMsg">Message:</textarea>
<label class="error" for="message" id="message_error">This field is required.</label>
</div>
<div>
<input class="button" type="submit" value="Submit" name="submit" />
</div>
JS:
<script type = "text/javascript">
$(function () {
$('.error').hide();
$("#contact-post").submit(function (event) {
alert("submitted");
event.preventDefault();
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var subject = $("input#subject").val();
var message = $("#message").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
} else if (email == "") {
$("label#email_error").show();
$("input#email").focus();
} else if (phone == "") {
$("label#phone_error").show();
$("input#phone").focus();
} else if (subject == "") {
$("label#subject_error").show();
$("input#subject").focus();
} else if (message == "") {
$("label#message_error").show();
$("input#message").focus();
} else {
var dataString = 'name=' + name + '&email=' + email + '&phone=' + phone + '&subject=' + subject + '&message=' + message;
$.ajax({
type: "POST",
url: "app/contact.php",
data: dataString,
success: function () {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function () {
$('#message').append("<img id='checkmark' src='web/images/check.jpg' />");
});
}
});
}
});
});
< /script>
That will work. Also I changed all of the value attributes in your HTML to placeholder attributes so they function as expected and don't get in the way of the validation.
Alternatively, since you're already using jQuery, you could check out jQuery Validate, a jQuery plugin that would make this much simpler
UPDATE:
I removed all of the onfocus/onblur attributes from your HTML and it works now. The JS in the onblur tags was filling the form with values, so it was able to pass validation. Look at this JSFIDDLE for a working verison
UPDATE 2:
The var message = $("input#message").val() should be var message = $("#message").val().
The first one is looking for an input with the id of "message", where as you have a textarea with that id. Changing this line will correct the blank message you're getting. (see the updated JS above)
Regarding this question,
I have noticed that in the first link I have the $(".button").submit(function (event) whereas in your config, in the same spot you have $("#contact-post").submit(function (event)
I have the validation being performed when a form with the id of "contact-post" gets submitted, instead of when the button gets submitted (which isn't possible). The reason the page with this JS/form is submitting is that the JS to validate never gets triggered.
It's possible (although unlikely) to submit the form without clicking that button, so we don't want the validation to be skipped on the off-chance that happens.
You could try adding "return true;" to the .click
$(".button").click(function () {
//...
//validation code
//...
//return true if passes validation
return true;
}
Have you thought about combining things like this:
$('yourForm').on('submit', function(event){
if ( formIsvalid() ) {
$.ajax({
...
});
} else {
// Do something else maybe?
}
event.preventDefault();
});
// Form validation.
function formIsvalid() {
... form validation here...
return true;
}

Categories