html - use onsubmit and action together - javascript

I want the form to post the credentials via a get request but have difficulties making it work together with the onsubmit parameter which is used to validate the data entered. This is my form code:
<form onsubmit="return formValidation()" action="show_get.php" method="get" name="registration">
This is the code I used for validation
function formValidation() {
var name = document.registration.name;
var uemail = document.registration.email;
{
if (allLetter(name)) {
if (ValidateEmail(uemail)) {
if (checkDate()) {
}
}
}
return false;
}
}
function allLetter(name) {
var letters = /^[A-Za-z]+$/;
if (name.value.match(letters)) {
return true;
}
else {
alert('Name must have alphabet characters only');
return false;
}
}
function ValidateEmail(uemail) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.value.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now) {
alert("Date must be in the future");
}
}

If you attach an onsubmit event handler and it returns false, the form will not be submitted. In your case, that always happens, even if the input is valid.
You check allLetter(), then ValidateEmail() and checkDate(), but you don't return true when they're all valid. Your code continues and it reaches return false;. The submit event handler returns the result of that validation function (which is false), so it returns false too. This tells the form to not submit.
Change your validation function to this:
function formValidation() {
var name = document.registration.name;
var uemail = document.registration.email;
if (allLetter(name) && ValidateEmail(uemail) && checkDate()) {
return true;
} else {
return false;
}
}
If all three checks return true, the validation function will return true as well and the form will be submitted.
Note: You had one unnecessary pair of brackets ({}), I removed them. I also improved readability by combining all the nested if statements into one.
Edit: Also, your checkDate() doesn't return true and false accordingly. It returns undefined by default, which is a falsy value. This means that it won't pass the validation function's && check and the form won't get submitted. Change checkDate() to this:
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now) {
alert("Date must be in the future");
return false;
} else {
return true;
}
}
Edit 2: You also incorrectly get the values of your input elements. When you do this:
var name = document.registration.name;
var uemail = document.registration.email;
You get the HTML element with name attribute name and HTML element with name attribute email. You should get the elements' values:
var name = document.registration.name.value;
var uemail = document.registration.email.value;
It's best to edit your answer and add the full HTML and JavaScript. There might be more problems.

Related

basic javascript form validation - validate same input types with same function

I have always used jQuery validate() for forms, but have run into a problem recently after an upgrade to our XMPie software (we do targeted communications).
The new version of XMPie requires jQuery 1.10.2 which is a version not supported by validate(), so I'm doing the validation manually.
I can easily validate by writing a separate function for each input, but it means re-writing at least some of the code to target a specific input name or id for example.
What I'm wondering is why can't I write a generic function for a specific input type (for example a simple text field) and let the input call the function on focusout(), passing itself as a parameter?
If I've got two text inputs, "fullName" and "userName" why can't I use
$(document).ready(function () {
var inputName = "";
var inputValue = "";
var inputAlert = "";
$("input").focusout(function () {
inputIdentify(this);
console.log(inputName);
inputGetValue(this);
console.log(inputValue);
if (this.type == "text") {
console.log("YES");
textValidate(inputName, inputValue);
}
});
function inputIdentify(theInput) {
inputName = theInput["name"];
console.log(inputName);
return inputName;
}
function inputGetValue(theInput) {
inputValue = theInput["value"];
return inputValue;
}
function textValidate(theInput, inputValue) {
console.log(theInput,inputValue);
var letters = /^[A-Za-z ]+$/;
if (inputValue.match(letters)) {
$(theInput).addClass("correct");
return true;
} else {
$(theInput).removeClass("correct");
$(theInput).addClass("incorrect");
// alert('Username must have alphabet characters only');
$(inputName).focus();
return false;
}
}
});
to remove and add simple css classes (coloured border) to indicate the problem fields?
Thanks and regards,
Malcolm
You're not passing the correct arguments to textValidate(). You're passing inputName as the theInput, but textValidate() uses $(theInput) to access the input element. You should pass this as that argument:
textValidate(this, inputValue);
Also, your use of global variables is poor design. Since inputIdentify() and inputGetValue() return values, you should assign the returned value to local variables, instead of having those functions set global variables.
$("input").focusout(function () {
var inputName = inputIdentify(this);
console.log(inputName);
var inputValue = inputGetValue(this);
console.log(inputValue);
if (this.type == "text") {
console.log("YES");
textValidate(this, inputValue);
}
});
function inputIdentify(theInput) {
var inputName = theInput["name"];
console.log(inputName);
return inputName;
}
function inputGetValue(theInput) {
var inputValue = theInput["value"];
return inputValue;
}

Global variable setting fails in JavaScript validation

I am getting an error while setting global variable flag inside function.
Global variable declaration
var flag = false;
Function to validate textbox
//To validate Product Name field
function Name() {
var pName = document.getElementById('addPName').value;
if (pName == "") {
$('#productNameError').text('Product Name is required');
flag = false;
}
else {
$('#productNameError').text('');
flag = true;
}
}
Function to validate quantity
//To validate Product Quantity Field
function Quantity() {
var pQty = document.getElementById('addPQty').value;
if (pQty != "") {
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
if (regex.test(pQty)) {
$('#productQtyError').text('');
flag = true;
}
else {
$('#productQtyError').text('Enter Quantity of the Product');
flag = false;
}
}
else {
$('#productQtyError').text('Quantity is required');
flag = false;
}
}
//Validation Summary
function validate() {
if (flag == true) {
$('#validationSummary').text('');
return true;
}
else {
$('#validationSummary').text('Please fill out required fields.');
return false;
}
}
I am calling first two functions on onfocusout event of textbox and calling validate() function on button click. The problem which I am facing is: inside the Quantity() flag is not getting set to false. Although the field remains blank,record gets inserted.
if you are getting flag=true in validate() then you may be calling Quantity() first ,it will set flag false then Name() which will set flag to true so It bypassed validate() function.
This is not the correct way, you are trying to achive validation. Consider scenario, when user have entered the correct value in first filed, flag will be set to true with the fact that second field is empty amd form will be submitted and hold true vice versa.
If want to achive by this way, keep as many flag variables as the number of fields amd chech all those variable inside validate.
Or, use '.each' to iterate each element and validate it and keep appending validation mesages to dom object.
Thanks
Don't use Global Variables
You're going to have a bad time if you use global variables, you can use the revealing module pattern to encapsulate some of the messiness
Would suggest something like this :
var app = app || {};
app.product = app.product || {};
app.product.validate = app.product.validate || {};
app.product.validate.isValid = false;
app.product.validate.name = function(){
var pName = document.getElementById('addPName').value;
if (pName == "") {
$('#productNameError').text('Product Name is required');
app.product.validation.flag = false;
} else {
$('#productNameError').text('');
app.product.validation.flag = true;
}
}
app.product.validate.quantity = function() {
var pQty = document.getElementById('addPQty').value;
if (pQty != "") {
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
if (regex.test(pQty)) {
$('#productQtyError').text('');
app.product.validate.flag = true;
} else {
$('#productQtyError').text('Enter Quantity of the Product');
app.product.validate.flag = false;
}
} else {
$('#productQtyError').text('Quantity is required');
app.product.validate.flag = false;
}
}
console.log is Your Friend
Try putting a console.log inside some of those methods, what I am guessing your issue is is that something is being called out of the order you expect and setting the flag to a value you aren't expecting.
Can do console.log statement like this console.log if you open up your developer console should show you the output from the console

Validate particular field / particular rule using Kendo UI validation

Current I have the following custom rules to validate fields of my form.
Rules
$scope.validator = $("#frmPreregistration").kendoValidator({
rules: {
varifySsn: function (input) {
var ret = true;
if (input.is("[name=last4Ssn]") && $scope.Last4DigitsSsn != undefined ) {
ret = $scope.validateSsnLast4Digit();
}
return ret;
},
varifyDob: function (input) {
var ret = true;
if (input.is("[name=dob]") && $scope.DateOfBirth != undefined ) {
ret = $scope.validateDateOfBirth();
}
return ret;
},
varifyZipCode: function (input) {
var ret = true;
if (input.is("[name=zipCode]") && $scope.ZipCode != undefined ) {
ret = $scope.validateZipCode();
};
return ret;
}
},
messages: {
varifySsn: $scope.resources.SsnLast4DigitDoesNotMatch,
varifyDob: $scope.resources.DobNotMatchWithSelectedUserType,
varifyZipCode: $scope.resources.ZipCodeNotMatchWithSelectedUserType,
}
}).data("kendoValidator");
I am validating the form whenever user enters a value in any of the field in the form by $scope.validator.validate()
This is resulting in firing the rules for all the fields even before the user enters any value into it.
Question
Is there any possibility that I can run a particular validation rule at a time or run validation for a particular field?
You can use validateInput for specific element.
Example:
$scope.validator.validateInput($("input[name=dob]"));
to hide invalid message you can use hideMessages function
$scope.validator.hideMessages();

jQuery make sure all form fields are filled

I have a simple form I'm making client side validation for.
To validate, none of the fields should be left blank.
This is how I go at it:
function validateForm() {
$('.form-field').each(function() {
if ( $(this).val() === '' ) {
return false
}
else {
return true;
}
});
}
For some reason, my function always returns false, even though all fields are filled.
You cannot return false from within the anonymous function. In addition, if it did work, you would return false if your first field was empty, true if not, and completely ignore the rest of your fields. There may be a more elegant solution but you can do something like this:
function validateForm() {
var isValid = true;
$('.form-field').each(function() {
if ( $(this).val() === '' )
isValid = false;
});
return isValid;
}
Another recommendation: this requires you to decorate all of your form fields with that formfield class. You may be interested in filtering using a different selector, e.g. $('form.validated-form input[type="text"]')
EDIT Ah, I got beat to the punch, but my explanation is still valid and hopefully helpful.
You were returning from the inner function not from the validate method
Try
function validateForm() {
var valid = true;
$('.form-field').each(function () {
if ($(this).val() === '') {
valid = false;
return false;
}
});
return valid
}
function validateForm() {
var invalid= 0;
$('.form-field').each(function () {
if ($(this).val() == '') {
invalid++;
}
});
if(invalid>0)
return false;
else
return true;
}
Here is a similar approach:
function validateForm() {
var valid = true;
$('.form-field').each(function() {
valid &= !!$(this).val();
});
return valid;
}
!! just converts input value to bool

Invalid left-hand side in assignment for simple login script

I have to build a simple login script for a js class.
I cannot get the loop to work. Everytime I type in any info it gives me "Invalid left-hand side in assignment"
When the login button is clicked the getData function gets the values of the boxes then passes them to the logon function that checks against the array. That's where the script stops. If I change the = in the if statement to == it will accept the last valid login f the array but none of the others.
What am I doing wrong?
<script type="text/javascript">
var userLogins = [{user:"user1", password:"pass1"},{user:"user2", password:"pass2"},{user:"user3", password:"pass3"}]
var success = null;
function logon(user, pass) {
userok = false;
for (i = 0; i < userLogins.length; i++)
{
if(pass = userLogins[i].password && user = userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
secret(success);
}
function getData() {
var user = document.getElementById("userid").value;
var password = document.getElementById("password").value;
logon(user, password);
}
function secret(auth){
if(auth)
{
show('success');
hide('login');
}
else
{
show('error');
hide('login');
}
}
function show(show) {
document.getElementById(show).className = "show";
}
function hide(hide) {
document.getElementById(hide).className = "hide";
}
If I change the = in the if statement to == it will accept the last valid login f the array but none of the others.
= is the assignment operator
== is the equality operator
You're confusing the two. You want the latter. Otherwise, your assigning the value which results returns the value itself (often a true value).
Per the comments, there's also the strict equality operator. For the difference between == and === this answer will blow your mind.

Categories