JavaScript form validation improvement - javascript

I have a user profile form with 15 text fields and some dropdown and an textarea. the scene is that user can input field in profile form. On save it is no necessary to fill all fields, whatever the user fills in fields i have to validate and save in database via ajax call.
for now i am using validation like this,
var first_name = document.getElementById('id_candidate_profile-first_name').value;
....
var status = false;
if(first_name != ''){
status = regex_test(first_name, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-first_name').innerHTML = "first name should only have alphabets";
}
else{
status = true;
}
}
if(middle_name != "" & status = true){
status = regex_test(middle_name, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-middle_name').innerHTML = "middle name should only have alphabets";
}
else{
status = true;
}
}
if (last_name != '' & status = true){
status = regex_test(last_name, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-last_name').innerHTML ="last name should only have alphabets";
}
else{
status = true;
}
}
if (date_of_birth != '' & status = true){
status = regex_test(date_of_birth, ck_date);
if(status==false){
document.getElementById('candidate_profile_error-date_of_birth').innerHTML ="date of birth should be in YYYY-MM-DD format";
}
else{
status = true;
}
}
if (birth_place != '' & status = true){
status = regex_test(birth_place, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-birth_place').innerHTML ="birth_place should only have alphabets";
}
else{
status = true;
}
}
if (nic != '' & status = true){
status = regex_test(nic, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-nic').innerHTML ="nic should be in this format 12345-1234567-1";
}
else{
status = true;
}
}
if (status = true) {
// made ajax call
}
function regex_test(variable, regex){
var _result = false;
if(!regex.test(variable)){
_result = false;
}
else {
_result = true;
}
return _result;
}
Can be seen that there are lots of nested if else involved that irritate me, need some better way to do this? any best alternative?

You could create an array of validation objects, each object containing properties reg_ex, field, error_msg_container_id and error_msg:
var validationRules = [
{ reg_ex: first_name,
field: ck_name,
error_msg_container_id: candidate_profile_error-first_name,
error_msg: "first name should only have alphabets" },
{ reg_ex: date_of_birth,
field: ck_date,
error_msg_container_id: candidate_profile_error-date_of_birth,
error_msg: "date of birth should be in YYYY-MM-DD format" }
];
In the validation function, you just iterate through the whole array. That also makes it easier to maintain further input fields which you might add later.
P.S.: If you don't know how to iterate over an array, let me know.
Edit: Since requested by OP, an iteration function would look similar to this:
function isFormDataValid() {
for (i=0; i< validationRules.length; i++) {
// do the validation inside here, it will be repeated once for each validation rule;
}
return status;
}
In case you need variable property names from the array to read/write, use this syntax
Object[variable]
where variable contains the string that is the name of the property you need to access.
var myObject = {
name: "peter",
age: 46
};
var validationRules = [ { fieldname: 'name'}, { fieldname: 'age' } ];
for (var i=0; i< validationRules.length; i++) {
alert(myObject[validationRules[i].fieldname]);
}

You can use any form validation library. I personally recommend Parsley.
There's a simple validation form example: http://parsleyjs.org/doc/examples/simple.html

Related

value of property in nested object JS

claimReservation function. It should:
If the reservation exists and is unclaimed, welcome the user (use
alert).
If the reservation exists and is already claimed, inform the user
about the situation (use alert).
If there is no reservation, tell the user there is nothing under
their name (user alert).
Use 'Bob' and 'Ted' to test your code.
my code :
var reservations = {
'Bob': { claimed: false },
'Ted': { claimed: true }
}
var name = prompt('Please enter the name for your reservation');
var claimReservation = function (name) {
if(reservations.claimed == "false"){
alert("Welcome")
}
else if(reservations.name.claimed == "true"){
alert("You have a problem bruh!")
}
else{
alert("No reservation by that name bruh")
}
}
claimReservation("Leeann");
claimReservation("Bob");
claimReservation("Ted")
`
Looks like you're trying to use a prompt to get the name and then reference "name" as the passed in variable to the function? Please see the updated code and let me know if you have any questions.
var reservations_ = {
'Bob': {
'claimed': false
},
'Ted': {
'claimed': true
}
};
var claimReservation = function(name) {
if (reservations_.hasOwnProperty(name) === false) {
alert("No reservation by that name bruh");
return;
}
if (reservations_[name].claimed === false) {
alert("Welcome " + name);
} else if (reservations_[name].claimed === true) {
alert(name + ", you have a problem bruh!");
}
};
claimReservation("Leeann");
claimReservation("Bob");
claimReservation("Ted");
var name = prompt('Please enter the name for your reservation');
claimReservation(name);

Pass Array as a parameter in Javascript

This function is used to check if the checkbox is selected or not.Can somebody help how to pass the array as a parameter to URL which will call a stored procedure.
function js_remove_masters(theForm) {
var vCheckedCount = 0;
var vContinue = true;
var mycheckedarr = [];
var myuncheckedarr = [];
//check to see if anything is selected
if ((theForm.selected.length == null) && (!(theForm.selected.checked))) {
vContinue = false;
alert("Please select an item to be deleted.");
} else if (theForm.selected.length != null) {
for (var i = 0; i < theForm.selected.length; i++) {
if (theForm.selected[i].checked) {
vCheckedCount = 1;
mycheckedarr.push = theForm.selected[i].value;
} else {
myuncheckedarr.push = theForm.selected[i].value;
}
}
if (vCheckedCount == 0) {
vContinue = false;
alert("Please select an item to be deleted.");
}
}
if (vContinue) {
theForm.action = ("library_search_pkg_nv1.remove_checkin_masters");
-- - here how to pass array parameters
theForm.submit();
}
}
procedure remove_masters(
masterID in smallarray
default smallempty,
masterIDunselected in smallarray
default smallempty
);
Just get rid of the JavaScript entirely. You are submitting the form.
If a checkbox is checked then its name/value pair will be included in the form data.
If it isn't checked, then it won't be.
If you have a bunch of checkboxes (or other elements) with the same name, then most server side form data parsing libraries will express that as an array automatically. The main exception is PHP which requires that you put [] on the end of the name first.

How to reject use of certain words in a form?

I am new to Javascript.
I need to make an username input, then validate it.
The username entered must not be one of the elements in this array: ["admin", "administrator", "demo", "user"] etc. The array can be longer.
I made this so far, but it works only for the 1st element in the array.
function arrayValidation () {
nonoUser = ["username", "admin", "administrator", "demo"];
valueOfInput = document.getElementById("user").value; // "user" here is id of input
for (var i = 0; i < nonoUser.length; i++) {
if (valueOfInput == nonoUser[i]) {
alert("you cant use this username");
}else {
return;
}
}
}
Try this:
function arrayValidation () {
nonoUser = ["username", "admin", "administrator", "demo"];
valueOfInput = document.getElementById("user").value; // "user" here is id of input
var isValid = true;
for (var i = 0; i < nonoUser.length && isValid; i++) {
if (valueOfInput == nonoUser[i]) {
isValid = false;
}
}
if (isValid) {
// Username is valid
}else{
// Username is invalid
}
}
However, you should never trust data that's sent to the server (Validate server-side as well)
It's trivial to change the js as a user.
This should point you in the right direction:
document.getElementById("user").onkeyup = function(){
var nonoUser = ["username", "admin", "administrator", "demo"];
nonoUser.indexOf(this.value) === -1 ? false : this.value = '';
}
demo: http://jsfiddle.net/Le2xC/
I also hope you're validating this server-side as well, otherwise users will still be able to use your "nono" usernames.
you need to add return false; to the code section with the alert, not the else statement.
The comments here should help you to see why your code isn't working as you expect:
// Your original code:
function arrayValidation () {
nonoUser = ["username", "admin", "administrator", "demo"];
valueOfInput = document.getElementById("user").value; // "user" here is id of input
for (var i = 0; i < nonoUser.length; i++) {
if (valueOfInput == nonoUser[i]) {
alert("you cant use this username");
} else {
// Using return here is the problem.
// This else block will run if a valid username was entered.
// The return statement stops execution of the function, thus ending the loop.
// So if the loop passes the test the first time, this return
// statement will stop the loop and function from completing
// the checks against the other keywords.
return;
}
}
}
This is your code modified to work as you expect:
function arrayValidation () {
nonoUser = ["username", "admin", "administrator", "demo"];
valueOfInput = document.getElementById("user").value; // "user" here is id of input
for (var i = 0; i < nonoUser.length; i++) {
if (valueOfInput == nonoUser[i]) {
alert("you cant use this username");
// We can end the function check return here.
// There's no point checking the others, as we've found an invalid one.
return false; // Return a meaningful result
}
// No need for an else statement either.
}
}
As many have pointed out, client side validation should be considered an optional extra, and server-side validation as essential.

Loading form input fields into a javascript array and then validating

I seem to be really stuck on something. I have a function to check if all the form input fields are equal to null or "" which is all fine but wanted to see if there is another way of doing it by loading all the fields into a javascript array and then doing a for loop along with an if statement to check if any of the fields are empty, unfortunately I can't seem to get this to work and wondering if I've simply just missed something some where. Here is my code:
function checkempty()
{
fname = document.getElementById("firstname").value;
lname = document.getElementById("lastname").value;
fage = document.getElementById("age").value;
addressl1 = document.getElementById("addressline1").value;
addressl2 = document.getElementById("addressline2").value;
ftown = document.getElementById("town").value;
fcounty = document.getElementById("county").value;
fpcode1 = document.getElementById("pcode1").value;
fpcode2 = document.getElementById("pcode2").value;
ftelephone = document.getElementById("telephone").value;
fcomment = document.getElementById("comment").value;
var myArray = [];
myArray[0] = fname;
myArray[1] = lname;
myArray[2] = fage;
myArray[3] = addressl1;
myArray[4] = addressl2;
myArray[5] = ftown;
myArray[6] = fcounty;
myArray[7] = fpcode1;
myArray[8] = fpcode2;
myArray[9] = ftelephone;
myArray[10] = fcomment;
for(i=0;i<myArray.length;i++)
{
if(!myArray[0])
{
return true;
}
}
return false;
}
I then use another function:
function checkform()
{
if(checkempty)
{
display_errormessage("One or more fields empty!");
}
else
{
alert("Thanks for you input!");
}
}
The display_errormessage() function is just one that puts an error message into a div at the top of the form to display an error message if the form is incomplete.
Can anyone see where i've gone wrong?
Thanks in advance for any help!
Dave.
First, function checkform is not called. The if (checkform) should be if (checkform()) or you will test only test the availability of the function, not the result.
Then the if (!myArray[0]) should be if (!myArray[i]) to not only test the firstname
Or better, if (myArray[i].length==0) to be sure to explicitly test for empty string and not just doing an implicit boolean conversion (javascript evaluate 0=="" as true)
if(!myArray[0]) should be if(!myArray[i]), but a larger point is you're only validating that the value isn't falsey (null, '', 0, false, etc.), not that it's appropriate for the task.
Guess you won't need this function as you've already fixed yours, but I'll leave it here as it may be helpful in the future. JSFiddle
function checkform()
{
arr1 = document.getElementsByTagName('input');
arr1 = Array.prototype.slice.call(arr1);
arr2 = document.getElementsByTagName('textarea');
arr2 = Array.prototype.slice.call(arr2);
arrs = arr1.concat(arr2);
for(i=0;i<arrs.length;i++)
{
if (arrs[i].type == "text" || arrs[i].type == "textarea")
{
if (arrs[i].value == '')
{
alert("Fill all fields before submitting!");
return false;
}
}
}
alert("Thanks for your input!");
return true;
}
According that your input fields are in the form named form:
var allTrue = [].every.call( document.forms.form.elements, function( el ) {
return !!el.value;
} );
if ( allTrue ) {
alert( "Thanks for your input!" );
}
else {
alert( "Some fields are missing!" );
}

'undefined' appearing in alert

I am using Javascript to validate some code, and it works fine, but whenever I call alert to show the errors, at the beginning of the alert message I get 'undefined'. So when I should expect the alert to show 'Please enter a Low Target', instead I get 'undefinedPlease enter a Low Target'. Can somebody tell me what is wrong with my code?
//validation
var lowTarget;
var highTarget;
var errorList;
var isValid = true;
lowTarget = $('input[name="txtLowTarget"]').val();
highTarget = $('input[name="txtHighTarget"]').val();
if (lowTarget == "") {
errorList += "Please enter a Low Target\n";
isValid = false;
}
else {
if (isNumeric(lowTarget) == false) {
errorList += "Low Target must be numeric\n";
isValid = false;
}
}
if (highTarget == "") {
errorList += "Please enter a High Target\n";
isValid = false;
}
else {
if (isNumeric(highTarget) == false) {
errorList += "High Target must be numeric\n";
isValid = false;
}
}
if (isValid == true) {
if (!(parseFloat(highTarget) > parseFloat(lowTarget))) {
errorList += "High Target must be higher than Low Target\n";
isValid = false;
}
}
if (isValid == false) {
alert(errorList);
}
Assign some default value to errorList, e.g. empty string
var errorList = "";
Until you do that, initial value of errorList is undefined.
I was finding the same problem in my project while using
var try2 = document.getElementsByName("y_email").value;
alert(try2);
Now I used the following and it works well
var try2 = document.getElementsByName("y_email")[0].value;
alert(try2);
(So Be doubly sure that what you are using in correct format to use.)

Categories

Resources