Compare viewbag value with string - javascript

I assigned value to a ViewBag.Form in a controller
ViewBag.Form = "In";
Now, I want to compare the value with string in javascript. So I do it like this
var form = "#ViewBag.Form";
if (form == "In")
{
//myCode
}
else
{
//myCode
}
But it always enter the else loop which mean form and ViewBag.Form doesnt match the value while it actually matched

please take viewbag in JavaScript in single quote
like this '#ViewBag.Form'
var form = '#ViewBag.Form';
if (form == "In")
{
//myCode
}
else
{
//myCode
}
or
assign ViewBag.Form value to hidden field
<input type="hidden" id="FormID" value="#ViewBag.Form" />
var form = document.getElementById('FormID'); //javascript
var form = $("#FormID").val(); //jQuery
if (form == "In")
{
//myCode
}
else
{
//myCode
}

Related

Javascript form validation only working once

Script: NewsletterScript.js
function formValidation() {
var fname = document.getElementById('firstName').value;
var lname = document.getElementById('lastName').value;
var pnumber = document.getElementById('phoneNumber').value;
var email = document.getElementById('e-mail').value;
if (FirstName(fname)) {
}
if (LastName(lname)) {
}
if (Country(country)) {
}
if (Email(email)) {
}
return false;
}
/*first name input validation*/
function FirstName(fname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( fname =="" || fname.match(letters)) {
text="";
message[0].innerHTML = text;
return true;
}
else {
text="First name should contain only letters";
message[0].innerHTML = text;
return false;
}
}
/*last name input validation*/
function LastName(lname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( lname =="" || lname.match(letters)) {
text="";
message[1].innerHTML = text;
return true;
}
else {
text="Last name should contain only letters";
message[1].innerHTML = text;
return false;
}
}
I'm trying to get this validation to loop until the criteria is fulfilled, currently this is only working once and if the button is clicked again it submits regardless. Button below.
Due to the script being so long its not letting me upload all of it, however its just got other validation such as phone number etc, Any help will be appreciated, cheers!
If what you want is that formValidation() returns true only when the four validation functions return true you sould write that instead of putting empty if statements :
return FirstName(fname) && LastName(lname) && Country(country) && Email(email);
This manner formValidation() will return false if one of them return false
You should consider using form onsubmit instead on the onclick on the submit button.
Instead of:
<input class="button" type="submit" value="Submit" name="submit" onClick="formValidation()" />
consider using the form submit and do not forget the return keyword:
<form onsubmit="return formValidation();" > /* ... */ </form>
Related Question: HTML form action and onsubmit issues

Stop form whitespace when user pressing submit

Okay, so I have a form. Applied a function to it.
All I want to do is when the form is submitted it launches the function, it checks to see if there is white space and throws out a message. I have the following:
function empty() {
var x;
x = document.getElementById("Username").value;
if (x == "") {
alert("Please ensure you fill in the form correctly.");
};
}
<input type='submit' value='Register' onClick='return empty()' />
<input type='text' id="Username" />
This is fine for if someone pressed the space-bar once and enters one line of whitespace, but how do I edit the function so that no matter how many spaces of whitespace are entered with the space-bar it will always throw back the alert.
Thanks in advance. I am very new to JavaScript. So please be gentle.
Trim the string before testing it.
x = document.getElementById("Username").value.trim();
This will remove any whitespace at the beginning and end of the value.
I have made a function for the same, i added another checks (including a regular expresion to detect multiples empty spaces). So here is the code:
function checkEmpty(field){
if (field == "" ||
field == null ||
field == "undefinied"){
return false;
}
else if(/^\s*$/.test(field)){
return false;
}
else{
return true;
}
}
Here is an example working with jquery: https://jsfiddle.net/p87qeL7f/
Here is the example in pure javascript: https://jsfiddle.net/g7oxmhon/
Note: the function checkEmpty still be the same for both
this work for me
$(document).ready(function() {
$('#Description').bind('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9 .]/gi,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
});
function checkEmpty(field) { //1Apr2022 new code
if (field == "" ||
field == null ||
field == "undefinied") {
return false;
} else if (/^\s*$/.test(field)) {
return false;
} else {
return true;
}
}

php and javascript form validation issue

I have created a form using bootstrap and am using javascript for form validation and then a php script to grab the post data and display it
the basic structure is the following and I have made this as minimal as I could to address this specific issue. The issue I am having is that the script to check for the form validation works perfectly in the <script> tags at the end of the body, but instead of preventing the page from being submitted as it should it still processes to the next page with the form's contents that are being made through the php post action when the form is indeed not filled out correctly.
Why is this? Should the form validation still not stop the page from moving on to the post data since the validation is returning false if the form has not been submitted correctly. All the form validation alerts pop up correctly and I;m getting no console errors after checking, or do I need to perform an additional check to only process the post data if the form is valid?
<html>
other tags.....
<body>
<form name = "OrderForm" action = "process_order.php" onsubmit = "orderbutton" method = "post">
a bunch of content, divs, checkboxes, etc
</form>
</body>
<script>
function CheckForm() {
var Name = document.getElementById("Name");
var fries = document.forms.OrderForm.FryRadio;
var fryyes = fries[0].checked
var fryno = fries[1].checked
var bool = true;
if ((Name.value == "" || Name.value == "Name") || (!(document.getElementById("SandwichRadio").checked || document.getElementById("WrapRadio").checked))) {
bool = false;
}
else if (!(fryyes || fryno)) {
bool = false;
}
if (!(bool)) {
alert("Please fill out all of the required fields.");
return false;
}
else {
alert("Your order is being submitted");
console.log("Submitted")
}
};
</script>
</html>
You should call function on submit , I dont know what are you doing with current onsubmit='...'
So use following, call function when you submit the form.
<form name = "OrderForm" action = "process_order.php" onsubmit = "return CheckForm()" method = "post">
a bunch of content, divs, checkboxes, etc
</form>
For demo : Check Fiddle
first of all what you can do is:
you do not need the !fryes in another if statement:
you can do it also in the first if:
if ((Name.value == "" || Name.value == "Name") || (!(document.getElementById("SandwichRadio").checked || document.getElementById("WrapRadio").checked)) || ( (!(fryyes || fryno))) {
bool = false;
}
also what you can do is if bool is false, disable your submit button if there is any?
you can also do an onchange on the texboxes, that way you can validate each text box or checkbox one by one. and have the bool true and false?
I did something like this on jquery long time ago, for validation, where I checked each texbox or dropdown against database and then validate, aswell..
The code is below
<script>
$(document).ready(function(){
var works=true;
//Coding for the captcha, to see if the user has typed the correct text
$('#mycaptcha').on('keyup',function(){
if($('#mycaptcha').val().length>=5){
$.post("user_test/captcha_check.php",
{
// userid: $("#userlogin").val(),
mocaptcha: $("#mycaptcha").val(),
},
function(data,status){
if(data==0){
document.getElementById("final_error").innerHTML="Captcha did not match";
works=false;
}
if(data==1){
works=true;
document.getElementById("final_error").innerHTML="";
}
});
}
});
//Works like a flag, if any mistake in the form it will turn to false
//Coding the submit button...
$('#submitbtn').on('click',function(){
var arrLang = [];
var arrPrf = [];
uid = $("#userid").val();
capc = $('#mycaptcha').val();
pwd = $("#pwd1").val();
fname = $("#fname").val();
lname = $("#lname").val();
email = $("#memail").val();
pass = $("#pwd2, #pwd1").val();
daysel = $('#dayselect').val();
monthsel = $('#monthselect').val();
yearsel = $('#yearselect').val();
agree_term = $('#agree_box').prop('checked');
//checks if the textboxes are empty it will change the flag to false;
if((!uid) || (!capc) ||(!fname) || (!lname) || (!email) || (!pass) || (!daysel) || (!monthsel) || (!yearsel) || (!agree_term)){
works=false;
}
if(!works){
document.getElementById('final_error').innerHTML ="<font size='1.3px' color='red'>Please fill the form, accept the agreement and re-submit your form</font>";
}
else{
works=true;
//A jquery function, that goes through the array of selects and then adds them to the array called arrLang
$('[id=lang]').each(function (i, item) {
var lang = $(item).val();
arrLang.push(lang);
});
//A jquery function, that goes through the array of select prof and then adds them to the array called arrprf
$('[id=prof]').each(function (i, item) {
var prof = $(item).val();
arrPrf.push(prof);
});
var data0 = {fname: fname, mlname : lname, userid : uid,password:pwd, emailid : email, mylanguage : arrLang, proficient : arrPrf, dob : yearsel+"-"+monthsel+"-"+daysel};
//var json = JSON2.stringify(data0 );
$.post("Register_action.php",
{
// userid: $("#userlogin").val(),
json: data0,
},
function(data,status){
if(data==1){
//alert(data);
window.location = 'Registered.php';
}
document.getElementById("userid_error").innerHTML=data;
});
}
});
//to open the agreement in a seperate page to read it..
$("#load_agreement").click(function () {
window.open("agreement.html", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
});
//A code that loads, another page inside the agreement div
$( "#agreement" ).load( "agreement.html" );
//This part here will keep generating, duplicate of the language and profeciency box, incase someone needs it
$('#Add').click(function(){
//we select the box clone it and insert it after the box
$('#lang').clone().insertAfter("#lang").before('<br>');
$('#prof').clone().insertAfter("#prof").before('<br>');
});
//this part here generates number 1-31 and adds into month and days
i=0;
for(i=1; i<=31; i++){
$('#dayselect').append($('<option>', {value:i, text:i}));
if(i<=12){
$('#monthselect').append($('<option>', {value:i, text:i}));
}
}
//this code here generates years, will work for the last, 120 years
year=(new Date).getFullYear()-120;
i = (new Date).getFullYear()-16;
for(i; i>=year; i--){
$('#yearselect').append($('<option>', {value:i, text:i}));
}
//Regex Patterns
var pass = /^[a-z0-9\.\-\)\(\_)]+$/i;
var uname = /^[a-z0-9\.\-]+$/i;
var mname = /^[a-z ]+$/i;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
//When the Last Name texbox is changing this will be invoked
$("#fname").keydown(function(){
//comparing the above regex to the value in the texbox, if not from the box then send error
if(!mname.test($("#fname").val())){
//fill the textbox label with error
document.getElementById("fname_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid FirstName</font>";
$("#fname").css("border-color","rgba(255,0,0,.6)");
works=false;
}
else{
$("#fname").css("border-color","rgba(0,255,100,.6)");
document.getElementById("fname_error").innerHTML="";
works = true;
}
});//end of fname onchange
//When the Last Name texbox is changint this will be invoked
$("#lname").keydown(function(){
//comparing the above regex to the value in the texbox
if(!mname.test($("#lname").val())){
//fill the textbox label with error
document.getElementById("lname_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid LastName</font>";
$("#lname").css("border-color","rgba(255,0,0,.6");
works=false;
}
else{
$("#lname").css("border-color","rgba(0,255,100,.6)");
document.getElementById("lname_error").innerHTML="";
works = true;
}
});//end of lname on change
//When the userid textbox is chaning,this will be invoked
$("#userid").keydown(function(){
//comparing the above regex to the value in the texbox
if(!uname.test($("#userid").val())){
//fill the textbox label with error
document.getElementById("userid_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid UserId</font>";
$("#userid").css("border-color","rgba(255,0,0,.6");
works=false;
}
/*
else if($("#userid").val().length<4){
//fill the textbox label with error
document.getElementById("userid_error").innerHTML="<font color='red' size='2px' family='verdana'>Minimum user length is 4</font>";
$("#userid").css("border-color","rgba(255,0,0,.6");
//disable the submit button
//$('#submitbtn').attr('disabled','disabled');
works=false;
}
*/
else{
$("#userid").css("border-color","rgba(0,0,0,.3)");
$.post("user_test/user_email_test.php",
{
// userid: $("#userlogin").val(),
userid: $("#userid").val(),
},
function(data,status){
document.getElementById("userid_error").innerHTML=data;
});
works = true;
}
});//end of change
//When the userid textbox is chaning,this will be invoked
$("#memail").keydown(function(){
//comparing the above regex to the value in the texbox
if(!emailReg.test($("#memail").val())){
//fill the textbox label with error
document.getElementById("email_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid Email</font>";
$("#memail").css("border-color","rgba(255,0,0,.6");
works=false;
}
else{
works = true;
$.post("./user_test/user_email_test.php",{
useremail: $("#memail").val(),
},
function(data,status){
document.getElementById("email_error").innerHTML=data;
$("#memail").css("border-color","rgba(0,255,0,.3)");
works = true;
});
}
});//end of change
//When the userid textbox is chaning,this will be invoked
$("#pwd2").keyup(function(){
//checking length of the password
if($("#pwd2").val().length<10){
document.getElementById("pwd_error").innerHTML="<font color='red' size='2px' family='verdana'>Please enter a password minimum 10 characters</font>";
//$('#submitbtn').attr('disabled','disabled');
$("#pwd1, pwd2").css("border-color","rgba(0,255,100,.6)");
works=false;
}
//checking if the password matches
else if($("#pwd1").val()!=$("#pwd2").val()){
document.getElementById("pwd_error").innerHTML="<font color='red' size='2px' family='verdana'>Passwords do not match</font>";
//$('#submitbtn').attr('disabled','disabled');
works=false;
$("#pwd1, pwd2").css("border-color","rgba(0,255,100,.6)");
}
else{
$("#pwd1, #pwd2").css("border-color","rgba(0,0,0,.3)");
document.getElementById("pwd_error").innerHTML="";
//comparing the above regex to the value in the texbox and checking if the lenght is atleast 10
if(!pass.test($("#pwd2").val())){
//fill the textbox label with error
document.getElementById("pwd_error").innerHTML="<font color='red' size='1px' family='verdana'>Your password contains invalid character, Please use: a-z 0-9.( )_- only</font>";
$("#pwd1, #pwd2").css("border-color","rgba(255,0,0,.6");
works = false;
}
else{
$("#pwd1 , #pwd2").css("border-color","rgba(0,255,100,.6)");
works = true;
}
}
});//end of change
});//end of document ready
</script>

loop through all fields and return false if validation of any one field fails jquery

I am facing big trouble resetting the flag variables. I am not sure where I am missing :(
I have a form with lots of text fields. I am trying to loop through all the fields and on blur of each of the field I am doing some validations. If any of the validation for any of the field fails it should not submit the form. But now I am having a big trouble doing this. If I have 3 fields and the first value I have entered wrong and next two fields if I have given correct, its submitting the form which should not be. Can somebody please help me in this?
var globalValid = false;
var validators = {
spacevalidation: function(val) {
if($.trim(val) != "")
return true;
else
return false;
},
//Other validation fns
};
$('#form1 .required').blur(function(){
var input = $(this);
var tmpValid = true;
input.each(function(){
var classReturn = true;
validatorFlag = true;
input.next('ul.innererrormessages').remove();
input.removeClass('required_IE');
if(firstTime)
{
input.addClass('valid');
}
if (!input.val()) {
input.removeClass('valid');
input.addClass('required');
var $msg = $(this).attr('title');
input.after('<ul class="innererrormessages"><li>'+$msg+'</li></ul>');
globalValid = false;
}
else{
if(this.className) {
var classes = this.className.split(/\s+/);
for(var p in classes) {
if(classes[p] in validators) {
tmpValid = (tmpValid && validators[classes[p]] (input.val())) ? tmpValid : false;
}
}
}
if(tmpValid == false){
input.removeClass('valid');
input.addClass('required');
var $msg = input.attr('title');
input.after('<ul class="innererrormessages"><li>'+$msg+'</li></ul>');
}
}
});
globalValid = tmpValid;
});
$('#form1').submit(function() {
var returnValue = true;
if(globalValid )
{
returnValue = true;
}
else{
returnValue = false;
}
alert("returnValue "+returnValue);
return returnValue;
});
Using this code, if I put a wrong value for first field and correct value for the other two fields, ideally it should return false. But its returning true. I think I am not properly resetting the flag properly
Checkout this example which provides the basic premise of what needs to occur. Each time the blur event is fired you must validate all three fields and store the result of their validation to a global variable.
HTML
<form>
<input />
<input />
<input />
<button type="submit">Submit</form>
</form>
Javascript
var globalValid = false; //Global validation flag
$("input").blur(function(){
//local validation flag
var tmpValid = true;
//When one input blurs validate all of them
$("input").each(function(){
//notice this conditional will shortcircuit if tmpValid is false
//this retains the state of the last validation check
//really simple validation here, required value less than 10
tmpValid = (tmpValid && this.value && this.value < 10) ? tmpValid:false;
});
//assign the result of validating all inputs to a global
globalValid = tmpValid;
});
$("form").submit(function(e){
//This is just here to make the fiddle work better
e.preventDefault();
//check the global validation flag when submitting
if(globalValid){
alert("submitted");
}else{
alert("submit prevented");
}
});
JS Fiddle: http://jsfiddle.net/uC3mW/1/
Hopefully you can apply the principles in this example to your code. The main difference is the code you have provided does not validate each input on blur.

How can I add `onsubmit="submitted=true;"` (property?) on my <form> if my javascript condition is not met

I have a <form> Its default property is submitted=false; and I have a statement
function checking() {
var empty = 0;
$('input[type=text]').each(function(){
if (this.value == "") {
empty++;
$("#error").show('slow');
}else{
//missing piece
}
})
So when the user clicks the button and the above statement is not satisfied, I want to add onsubmit="submitted=true;" in my <form> and make it something like this <form onsubmit="submitted=true;".
If I don't get you wrong, you want to run that check and if it went well you want to set a variable named submitted to TRUE, and set it to FALSE otherwise.
If so, you could do it this way:
function checking() {
var empty = 0;
$('input[type=text]').each(function(){
if (this.value == "") {
empty++;
$("#error").show('slow');
}
});
if(empty > 0) submitted = false;
else submitted = true;
}
If that's not the case. If you wanted to show an error if there's an empty field and prevent the form from submitting if there's an empty field, so you should do it this way:
function checking() {
var empty = 0;
$('input[type=text]').each(function(){
if (this.value == "") {
empty++;
$("#error").show('slow');
}
});
return empty == 0;
}

Categories

Resources