JavaScript Multiple Entry Form Validation - javascript

I am trying to use Javascript to validate user input before page redirects.
Users can either Input Student ID, Name, or Gender, and based on their input, they will be redirected to a URL.
However, I don't seem to get the multiple entries correctly in my javascript and nothing happened when the submit button is clicked.
I have tried different solutions which I found here.
see my JavaScript code below;
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate(){
var username = document.getElementById("studentid").value;
if ( studentid == "12345" || studentid == "Daniel" || studentid == "Boy"){
alert ("Correct Input");
window.location = "https://www.google.com";
// Redirecting to other page.
return false;
}
else{
attempt --;// Decrementing by one.
alert("ATTENTION!\nInvalid student ID!\nNot associated with any student\nYou have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("studentid").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
I have tried to use the solutions below;
if ( studentid == "#12345, #Daniel, #Boy"));{
alert ("correct input");
window.location = "https://www.google.com";
// Redirecting to other page.
if ( studentid == '12345', 'Daniel', 'Boy'){
alert ("correct input");
window.location = "https://www.amazon.com";
// Redirecting to other page.

After so many attempts, I finally got it right!
var attempt = 3;
function check(form)
{
if(form.studentid.value == "12345" || form.studentid.value == "DANIEL" || form.studentid.value == "BOY")
{
window.location.replace('https://www.google.com')
return false;
}
else
{
attempt --;// Decrementing by one.
alert("ATTENTION!\nInvalid student ID!\nNot associated with any student!\nYou have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("studentid").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}

Related

jQuery / JavaScript test for email && checkbox validation

How do I test for form validation for both variables: emailAddr && items[].
items[] is a checkbox array.
Currently the code below won't submit the form at all.
jQuery(document).ready(function(){
var re = /(\w+)\#(\w+)\.[a-zA-Z]/g;
var email = document.getElementById("emailAddr");
var emailValue = email.value;
var testEmail = re.test(emailValue);
jQuery("#submitForm").on("click",function(){
if (jQuery("input[name*='items']").is(":checked"),
testEmail === true){
return true;
} else {
jQuery('#messages').append("You must choose at least 1 image<br>
Please enter a valid email");
return false;
}
});
});
Cleaning up the code a little to check for the value on submission may help but I do not know exactly how the html is formatted to see why else the form may not be submitting.
var re = /(\w+)\#(\w+)\.[a-zA-Z]/g;
var email = document.getElementById("emailAddr");
jQuery("#submitForm").on("click",function(e){
var emailValue = email.value;
var testEmail = re.test(emailValue);
if (jQuery("input[name*='items']").is(":checked") && testEmail === true){
return true;
} else {
e.preventDefault(); // prevents the form from submitting if invalid
jQuery('#messages').append("You must choose at least 1 image<br>Please enter a valid email");
return false;
}
});

JavaScript validate various form elements

I have a script thats trying to validate some form elements but i cant figure out the correct syntax for each "if" I need, its doing absolutely nothing. I believe the issue may be that on the same form there are many "tabs" or other forms so I may have to write which form the element belongs to but I dont know the syntax for that, like if its
var NewStatus = document.getElementById("ChangeStatusForm.CURRENT_STATUS").VALUE;
if none of the alerts apply then i just need it to submit the form
<script type="text/javascript">
function ValidateInfo()
var NewStatus = document.getElementById("CURRENT_STATUS").VALUE;
var OldStatus = document.getElementByID("ovpInfo.current_status").VALUE;
var CheckNumber = document.getElementByID("check_number").VALUE;
var CheckDate = document.getElementByID("check_date").VALUE;
if (NewStatus == 0){
alert ("Please select a New Status");
}
else if (NewStatus == 5){
alert ("This claim has already been collected");
} else if (NewStatus == 10){
alert ("This claim has already been collected");
} else if (NewStatus == 10 and CheckNumber =="" or CheckDate == ""){
alert ("Please enter Payment Details");
else
document.forms['ChangeStatusForm'].submit() ;
}
</script>
In order to just get at least one variable check working ive edited my script. this does not work either though (used some syntax I found to specify the actual form the element belongs to)
<script type="text/javascript">
function ValidateInfo()
{
var NewStatus = document.forms["ChangeStatusForm"]["CURRENT_STATUS"].value;
if (NewStatus == 0){
alert ("Please select a New Status");
}
}
</script>
you are using a wrong expression for "document.getElementById("id")" and you need to change the or, and for "&&", "||".
And I using a flag for return the correct value.
for example:
function ValidateInfo()
var flag = true;
var NewStatus = document.getElementById("CURRENT_STATUS").value;
var OldStatus = document.getElementByID("ovpInfo.current_status").value;
var CheckNumber = document.getElementByID("check_number").value;
var CheckDate = document.getElementByID("check_date").value;
if (NewStatus == 0){
alert ("Please select a New Status");
flag=false;
}
else if (NewStatus == 5){
alert ("This claim has already been collected");
flag=false;
} else if (NewStatus == 10){
alert ("This claim has already been collected");
flag=false;
} else if (NewStatus == 10 and CheckNumber =="" or CheckDate == ""){
alert ("Please enter Payment Details");
flag=false;
}else{
flag=true;
}
if( flag ){document.forms['ChangeStatusForm'].submit()}
good luck

validating custom domain for signup form using javascript?

I am trying to validate my company email-id's in sign up form...so that the form accepts only my company mail id...so now whats the problem here is after validating(ie; when we click submit button then we get an alert message) the form is getting refreshed and the entered values are cleared...so any help or suggestions so that it is not refreshed??thanks in advance...
My Javascript method is:
function submitAlbum() {
var frm = document.getElementById("frmRegistration");
//validateEmail(document.getElementById('email').value);
var email = document.getElementById('email').value;
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
// alert('Submission was successful.');
var r = confirm("Are You Sure You Want to add your details.");
if (r == true) {
frm.action = "signUpServlet?formidentity=doRegistration&checkboxStatus=" + checkboxStatus;
frm.submit();
}
}
else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
return false;
}
}
else {
document.getElementById('email').focus();
alert('Not a valid e-mail address.');
return false;
}
}
I think this will do the job.
<input type = "email" pattern ="^[a-z0-9._%+-]+#bdisys.com">
Check this bin
http://jsbin.com/dew/5/edit
You should bind your validation method to the submit event of your form.
Inside the validation method, stop the event to propagate if the field is invalid, or let it bubble if it's ok.
var frm = document.getElementById("frmRegistration");
frm.addEventListener('submit', validate, false);
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function validate(event) {
// validateEmail
var email = document.getElementById('email').value;
var confirmed = false;
if (re.test(email)) {
confirmed = true;
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
confirmed = confirm("Are You Sure You Want to add your details.");
}
} else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
}
if (!confirmed) {
event.preventDefault();
event.stopPropagation();
return false;
}
}
I suggest you to use jQuery to make your code simplier and before all portable.

If Statement Not Acting As Expected

$(document).ready(function(){
logger();
});
function logger()
{
if(localStorage.getItem("status") === null)
{
$("#test").html("Not logged in.");
$("#buttonlogin").click(function(){
var ul = $("#userlogin").val();
var pl = $("#passlogin").val();
$.post("includes/logger.php", {type : "login", user : ul, pass : pl}, function(dlogin){
if(dlogin == 1)
{
$("#outlogin").html("Please enter a username.");
$("#userlogin").focus();
}
else if(dlogin == 2)
{
$("#outlogin").html("Please enter password.");
$("#passlogin").focus();
}
else if(dlogin == 3)
{
$("#outlogin").html("This username doesn't exist.");
$("#userlogin").focus();
}
else if(dlogin == 4)
{
$("#outlogin").html("This username and password don't match.");
$("#userlogin").focus();
}
else
{
localStorage.setItem("status", dlogin);
logger();
}
});
});
$("#buttonregister").click(function(){
var ur = $("#userregister").val();
var pr = $("#passregister").val();
var cpr = $("#confirmpassregister").val();
$.post("includes/logger.php", {type : "register", user : ur, pass : pr, cpass : cpr}, function(dregister){
if(dregister == 1)
{
$("#outregister").html("Please enter a username.");
$("#userregister").focus();
}
else if(dregister == 2)
{
$("#outregister").html("Please enter a password.");
$("#passregister").focus();
}
else if(deregister == 3)
{
$("#outregister").html("Please enter a confirm password.");
$("#cpassregister").focus();
}
else if(dregister == 4)
{
$("#outregister").html("Password and confirm password do not match.");
$("#passregister").focus();
}
else if(dregister == 5)
{
$("#outregister").html("This username is already taken.");
$("#userregister").focus();
}
else
{
localStorage.setItem("status", dregister);
logger();
}
});
});
}
else
{
$("#test").html("You are logged in.");
$("#buttonlogout").click(function(){
localStorage.removeItem("status");
logger();
});
}
}
The above code is meant to check whether or not a localStorage variable is in existence or not. If it is then only allow the log out button to be pressed. If is doesn't then let the two forms to work. Once it is done with either it is supposed to recheck if the variable is set and then do as I said above. However it ignores it when a user logs in and allows the forms to run. If you refresh however it works fine. I cannot for the life of me figure out why this is happening, and it is beginning to piss me off. Any help would be appreciated.
On your else statement, try adding:
$('#buttonlogin').unbind('click');
$('#buttonregister').unbind('click');
If I understand your problem correctly, what's happening is those events are registered when you first run $("#buttonlogin").click(function()....
It doesn't matter that you call logger() again and the if statement is false the second time around. If you want to disable these callbacks you have to do it explicitly.

Javascript validation to open javascript alert on success?

First off, I don't know much about JS so please be patient with me.
I found this free validation JS and implemented it into my website, however, after a successful validation it doesn't tell you the form has been submitted.
My question is, is it possible to make this validation summon Apprise.js alert on a successful validation? Apprise
$(document).ready(function(){
//global vars
var form = $("#ContactForm");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var subject = $("#subject");
var subjectInfo = $("#subjectInfo");
var message = $("#message");
//On blur
name.blur(validateName);
email.blur(validateEmail);
subject.blur(validateSubject);
//On key press
name.keyup(validateName);
subject.keyup(validateSubject);
message.keyup(validateMessage);
//On Submitting
form.submit(function(){
if(validateName() & validateEmail() & validateSubject() & validateMessage())
return true
else
return false;
});
//validation functions
function validateEmail(){
//testing regular expression
var a = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//if it's valid email
if(filter.test(a)){
email.removeClass("error");
emailInfo.text("");
emailInfo.removeClass("error");
return true;
}
//if it's NOT valid
else{
email.addClass("error");
emailInfo.text("Please type a valid e-mail address!");
emailInfo.addClass("error");
return false;
}
}
function validateName(){
//if it's NOT valid
if(name.val().length < 4){
name.addClass("error");
nameInfo.text("Name must be atleast 4 letters (include last name)!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else{
name.removeClass("error");
nameInfo.text("");
nameInfo.removeClass("error");
return true;
}
}
function validateSubject(){
//if it's NOT valid
if(subject.val().length < 4){
subject.addClass("error");
subjectInfo.text("Subject must be atleast 4 characters!");
subjectInfo.addClass("error");
return false;
}
//if it's valid
else{
subject.removeClass("error");
subjectInfo.text("");
subjectInfo.removeClass("error");
return true;
}
}
function validateMessage(){
//it's NOT valid
if(message.val().length < 1){
message.addClass("error");
return false;
}
//it's valid
else{
message.removeClass("error");
return true;
}
}
});
You can add a prompt dialog box alert('Your Email has been sent.'); before return true, in form.submit function.

Categories

Resources