I have a multistep form needs additional validation for password, email, credit card expiry date.
As there is a function validateForm I want to add to this so that it also checks the password has 8 char and email is valid ('#').
The main issue is the for loop that says input is valid/invalid before allowing user to go to next step in form. At the moment it just checks if there is anything in each box, if so it goes next page. I need it to also check that the password/email is valid as per above requests.
var currentTab = 0;
showTab(currentTab);
function showTab(n) { /*need to add in password/email validation to below but unsure how */
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Complete Order";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
fixStepIndicator(n)
}
function nextPrev(n) {
var x = document.getElementsByClassName("tab");
if (n == 1 && !validateForm()) return false;
x[currentTab].style.display = "none";
currentTab = currentTab + n;
if (currentTab >= x.length) {
document.getElementById("orderForm").submit();
return false;
}
showTab(currentTab);
}
function validateForm() {
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
for (i = 0; i < y.length; i++) {
if (y[i].value == "") {
y[i].className += "invalid";
valid = false;
}
}
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid;
}
Assuming you can edit the HTML elements and add id's to the input fields, you can simply use document.getElementById to get each specific input.
<html>
<body>
<input type="password" id="myPassword" />
<input type="email" id="myEmail" />
</body>
</html>
function validateForm() {
const pwInput = document.getElementById('myPassword');
if( pwInput && pwInput.value.length < 5) {
console.log('password not valid');
}
const emailInput = document.getElementById('myEmail');
if(emailInput && emailInput.search(/#/) === -1) {
console.log('email not valid');
}
}
This sounds like homework, so this is some additional food for thought for production code.
While doing password validation on the client side is okay, server side must absolutely do password validation.
Email validation is very tricky to do. You can use a regex you find, but even the ones on Stack Overflow are filled with caveats and test cases that don't work. For production code, using a library along with email verification is your best bet.
Related
Im creating an asp.net booking page that has a coda slider effect,the page is also a content page of a master page, i have this JavaScript that allows the slider effect
<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form ...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
// ... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
document.getElementById("Submit").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("Submit").style.display = "inline";
document.getElementById("prevBtn").style.display = "none";
document.getElementById("nextBtn").style.display = "none";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
// ... and run a function that displays the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return true;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form... :
if (currentTab >= x.length) {
//...the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false:
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class to the current step:
x[n].className += " active";
}
</script>
The problem is that i have this button for a file Upload control that does a postback to display a label to show if the file is uploaded
<input type="submit" runat="server" class="btn btn-success" value="Upload File" onserverclick="Button1_Click"/>
but the page current tab returns to the first tab after post back, how can i prevent this from happening? this is the code that runs after i have clicked the "Upload File" button
protected void Button1_Click(object sender, EventArgs e)
{
if (payment.HasFile)
{
string FileExtention = Path.GetExtension(payment.FileName);
if (FileExtention.ToLower() != ".pdf" && FileExtention.ToLower() != ".docx")
{
message2.Visible = true;
message3.Visible = false;
message.Visible = false;
message1.Visible = false;
}
else
{
int FileSize = payment.PostedFile.ContentLength;
if (FileSize > 2097152)
{
message3.Visible = true;
message2.Visible = false;
message.Visible = false;
message1.Visible = false;
}
else
{
payment.SaveAs(Server.MapPath("~/ApplicantUploads/" + payment.FileName));
message.Visible = true;
}
}
}
else
{
message1.Visible = true;
message3.Visible = false;
message.Visible = false;
message2.Visible = false;
}
}
As a general technique, define a hidden field:
<asp:HiddenField ID="HiddenField" runat="server" value="" />
Create a javascript function to save the current tab position:
function SaveTabPosition(position) {
document.getElementById('<%=HiddenField.ClientID%>').value = position;
}
When the POST will take place, it will send also the "currentTab" value stored in HiddenField back to the server. In the response now you will have to use:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "setTabPosition", "var currentTab="+HiddenField.Value, true);
Now you should have the tab position back on the client side in "currentTab" variable. As a small mention, the "currentTab" should be accessible.
I am trying to do few validations in a form and it is not up to the mark. I need to hide the error message message of the name and show only email error. But it is not happening. Maybe you will understand from the code.
Here it is.
function validateform(form){
event.preventDefault();
console.log(form);
var i;
var fname = form.name.value;
var email = form.email.value;
var message = form.getElementsByClassName("error-message");
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (fname==null || fname==""){
for (i = 0; i < message.length;i++)
{
form.getElementsByClassName("error-message")[i].innerHTML="Please Enter Name";
return false;
}
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
for (i = 0; i < message.length;i++)
{
form.getElementsByClassName("error-email")[i].innerHTML="The email address you've entered contains an incorrect character. Please check this information and try again.";
return false;
}
}
else if (fname!=null || fname!=""){
for (i = 0; i < message.length;i++)
{
form.getElementsByClassName("error-message")[i].style.display = "none";
return false;
}
}
HTML
<form name="ccform" method="post" onsubmit="validateform(this)">
<p class="customer-name">Name</p>
<input type="text" class="input-name" name="name"></input>
<p class="error-message"></p>
<p class="customer-name">Email</p>
<input type="text" class="input-name" name="email" placeholder="e.g. name#emailaddress.com"></input>
<p class="error-email"></p>
<button type="submit" class="submit-button">Submit</button>
</form>
I want to hide error-message and show only error-email when name is entered,email is not entered and i press submit button.
P.S: Please no jQuery.
You have trying to hide error_message class in an else if condition. The code will not parse through all the if conditions. In your case, you want to show the email validation message and hence it will enter the second condition and will not enter the third condition. Refer the usage of if-else if-else statement here. You just try to merge the second and third condition together as follows.
if (fname==null || fname==""){
for (i = 0; i < message.length;i++)
{
form.getElementsByClassName("error-message")[i].innerHTML="Please Enter Name";
form.getElementsByClassName("error-message")[i].style.display = "block";
return false;
}
} else {
form.getElementsByClassName("error-message")[i].style.display = "none";
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
for (i = 0; i < message.length;i++)
{
form.getElementsByClassName("error-email")[i].innerHTML="The email address you've entered contains an incorrect character. Please check this information and try again.";
form.getElementsByClassName("error-email")[i].style.display = "block";
return false;
}
} else {
form.getElementsByClassName("error-email")[i].style.display = "none";
}
Hope it helps.
This is what worked for me.
function validateform(form){
var i;
var fname = form.name.value;
var email = form.email.value;
var message = form.getElementsByClassName("error-message");
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (fname==null || fname==""){
for (i = 0; i < message.length;i++)
{
form.getElementsByClassName("error-message")[i].innerHTML="Please enter your name";
form.getElementsByClassName("error-message")[i].style.display = "block";
form.getElementsByClassName("error-email")[i].style.display = "none";
return false;
}
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
for (i = 0; i < message.length;i++)
{
form.getElementsByClassName("error-email")[i].innerHTML="The email address you've entered contains an incorrect character. Please check this information and try again.";
form.getElementsByClassName("error-message")[i].style.display = "none";
form.getElementsByClassName("error-email")[i].style.display = "block";
return false;
}
}
I'm making a register page using HTML, CSS and JS and Java servlet etc. I have a monitorer() function which checks if the user has finished inputting everything before making the register button visible. But now everything works, but somewhere am getting screwed over and the button never comes back..
my button in reg.html :
<input type="submit" value="Register" class="btnSub" id="btnReg" style="visibility:hidden;"/>
javascript function monitorer()
function monitorer() {
var btnReg = document.getElementById("btnReg");
btnReg.style.visibility = "hidden";
var flag = true;
if (document.getElementById("fname").value.length >= 3) {
if (document.getElementById("lname").value.length >= 3) {
if (valiDate(document.getElementById("dob"))) {
if (document.getElementById("USN").value.length == 10) {
if (document.getElementById("passw").value.length > 5) {
var ticks = document.getElementsByClassName("checker"), i = 0;
for (i = 0; i < ticks.length; i++) {
if (ticks.item(i).innerHTML == "✔") {
alert("i val = " + i);
continue;
} else {
flag = false;
break;
}
}
}
} else {
flag = false;
document.getElementById("USN").focus();
}
} else {
flag = false;
document.getElementById("dob").focus();
}
} else {
flag = false;
document.getElementById("lname").focus();
}
} else {
flag = false;
document.getElementById("fname").focus();
}
if (flag == true) {
btnReg.style.visibility = "visible";
} else if(flag == false) {
btnReg.style.visibility = "hidden";
}}
And to help you get as good a picture as you can, a screenshot
See - all the ticks are there, the first name, last name etc are having value.length >=3 but still the register button doesn't show..
Also, I have put the monitorer() method in every input's "onBlur", "onChange" events.
Here is a link to my html file >>> reg.html
and please let me know if i can improve anything?
I am having trouble validation a form and staying on the same page. Below is my javascript validation which is working as i get popups.
function valueChecks(input){
var reqdFields = false;
var ncFields = false;
var catCheck = false;
var refCheck = false;
var dtCheck = false;
var retval = false;
reqdFields = checkRequiredFields(input) ;
ncFields = checkNonComplianceFields(input);
catCheck = checkCat();
refCheck = checkRef();
dtCheck = subDate();
var mesgNo="0";
if (reqdFields == true){
mesgNo="0";
} else { mesgNo="1";
}
if (catCheck == true){
mesgNo=mesgNo+"0";
} else { mesgNo=mesgNo+"2";
}
if (refCheck == true){
mesgNo=mesgNo+"0";
} else { mesgNo=mesgNo+"3";
}
if (dtCheck == true){
mesgNo=mesgNo+"0";
} else { mesgNo=mesgNo+"4";
}
if (ncFields == true){
mesgNo=mesgNo+"0";
} else {mesgNo=mesgNo+"5";
}
if (mesgNo =="00000"){
retval=true;
}
else if ((mesgNo =="10000")||(mesgNo =="12000")||(mesgNo =="12300")||(mesgNo =="12340")||(mesgNo =="12345")||(mesgNo =="10300")||(mesgNo =="10340")||(mesgNo =="10040")){
retval = false;
alert("Please check that you have filled in all the Mandatory Fields");
}
else if ((mesgNo =="02000")||(mesgNo =="02300")||(mesgNo =="02040")||(mesgNo =="02340")||(mesgNo =="02345")){
retval = false;
}
else if ((mesgNo =="00300")||(mesgNo =="00340")||(mesgNo =="00345")){
retval = false;
alert ("Please enter at least one Reference Value (File Number, STT or BL Number)");
}
else if ((mesgNo =="0004")||(mesgNo =="00045")){
retval = false;
alert ("The Incident Date must be less than or equal today's Date");
}
else if ((mesgNo =="0005")){
retval = false;
alert ("Please enter at least one Non Conforming Party");
}
return retval;
}
And this is how i declare my form.
<html:form action="/qaeditsrl" onsubmit="return valueChecks(this);" >
<input type=submit value="Submit" name="method" >
Can someone tell me why this is going wrong?
Try changing the submit button to input type=button.
Remove the onsubmit on the form, and add an id.
Then add onclick on the button doing all the checks,
if no errors were found use document.getElementById('formId').submit() for submitting;
I am trying to do a Javascript form validation, and I want to set the formValue to 0 in several cases. That is, if ANY of the required fields are not filled out, the value should go to 0.
function formValidation() {
var formValue = 1;
if (document.getElementById('orgname').value == '') formValue = 0;
else if (document.getElementById('culture[]').value == '') formValue = 0;
else if (document.getElementById('category[]').value == '') formValue = 0;
else if (document.getElementById('service[]').value == '') formValue = 0;
if (formOkay == 1) {
return true;
} else if (formOkay == 0) {
alert('Please fill out all required fields');
return false;
}
}
Is there a more elegant way to do this?
EDIT: Script does not appear to be working, now.
You can do some looping:
var toCheck = ['orgname', 'culture[]', 'category[]', 'category[]']
for(var id in toCheck )
{
if(document.getElementById(id).value == ''){
formValue = 0;
break;
}
}
A more elegant way can be that you specify a 'required' class on each input that you want to check and than do the following using jQuery:
$(document).ready(function(){
var toCheck = $('.required');
var formValue = 1;
$.each(toCheck, function(index, element){
if(element.val() == '')
formValue = 0;
});
});
I've done this in other languages using boolean logic, taking advantage of the & operator. It always returns false if any of the values are false.
Something like:
function formValidation() {
var formValue = true;
formValue &= document.getElementById('orgname').value != '';
formValue &= document.getElementById('culture[]').value != '';
formValue &= document.getElementById('category[]').value != '';
formValue &= document.getElementById('service[]').value != '';
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
This has the advantage of working for other scenarios where your logic is more complicated. Anything that evaluates in the end to true/false will fit right in with this solution.
Then I'd work on reducing logic duplication:
function formValidation() {
var formValue = true;
var elementIdsToCheck = ['orgname', 'culture[]', 'category[]', 'category[]'];
for(var elementId in elementIdsToCheck) {
formValue &= document.getElementById(elementId).value != '';
}
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
Something like this should help (this assumes that value attribute is available on the referenced elements):
var ids = ["orgname", "culture[]", "category[]", "service[]"],
formValue = 1; // default to validation passing
for (var i = 0, len = ids.length; i < len; i++) {
if (document.getElementById(ids[i]).value === "") {
formValue = 0;
break; // At least one value is not specified so we don't need to continue loop
}
}
Building upon #Baszz's second answer using jQuery, you could also build a more generic solution using HTML5 data- attributes:
$(function() {
$('form').submit(function() {
var toValidate = $(this).find('input[data-validation]');
for(var i=0; i<toValidate.length; i++) {
var field = $(toValidate[i]);
if(field.val().search(new RegExp(field.data('validation'))) < 0) {
alert("Please fill out all required fields!");
return false;
}
}
});
});
You can then specify regular expressions in your markup:
<form>
<input type="text" data-validation=".+" />
</form>
For required fields you can use ".+" as a regular expression, meaning the user has to enter at least one character, but you can of course use the full potential of regular expressions to check for valid email addresses, phone numbers or zip codes etc...