Why my form doesn't validate the fields? - javascript

I can't see a clear mistake in this code. Instead of validating my fields, it just tries to send my form and I don't know why.
This is my jsFiddle: http://jsfiddle.net/PAALA/
Other question, how to validate if select box was picked?

Firstly, because of how JSFiddle works, defining a function with function foo() {...} is unreliable. Instead, use foo = function() {...} syntax.
Next, you have an error in your script when you try to access document.forms["bug_form"]["Project"].value - there is no text input with that name.
Finally, to prevent accidental submission, do this:
validateBugForm = function() {
try {
// ALL YOUR ORIGINAL CODE HERE
}
catch(e) {
alert("An error occurred: "+e);
return false;
}
}
This will ensure that false is returned, even if your code errs.

The Javascript code is crashing out on the third line when you try to get the value for "Project". Looks like you forgot to give that one a name.

Related

How does prototype work for onSubmit:function()?

I was working on Co-drops Minimal Form Interface. I couldn't understand this code snippet in stepsForm.js. (Line 50)
stepsForm.prototype.options = {
onSubmit : function() { return true; }
};
I am new to JS, and wouldn't mind an explanation of the entire code in stepsForm if anyone has the time to do so. But, for the time being, an explanation for the above can do wonders for me. I know what a prototype is, but the onSubmit part is going over my head. I read on another question that this is to prevent refresh, but I feel that is wrong.
The library exposes options property that you may/can use to pass your own overriding values.This one in particular, exposes onSubmit.
For any html form an onSubmit is called when the submit action is invoked by another function or by click.
In the library the default onSubmit is returning true, meaning just execute the action. This can be overriden with you custom function like this...
<script>
var FORM_ELEMENT = document.getElementById( 'myForm' )
new stepsForm(FORM_ELEMENT, {
onSubmit :
function (FORM_ELEMENT) {
alert('You are about to submit the form ');
//manipulate your form or do any preprocess work...
return true;
});
</script>
Within the library the _submit (line 196 stepForm.js) is called which inturn calls the onSubmit. This time, instead of the default, it will execute the one we added above.
stepsForm.prototype._submit = function() {
this.options.onSubmit(this.el);
}
Hope that helps.

Getting all table rows and returning them using an XPath query in CasperJS

I'm using Casper.js to automate a regular upload. I've managed to upload the file and check if it's valid, but I'd like to parse the table which is returned if there's errors, but I get the error [error] [remote] findAll(): invalid selector provided "[object Object]":Error: SYNTAX_ERR: DOM Exception 12. Here's the relevant part of my code:
casper.then(function() {
if (this.fetchText('.statusMessageContainer').match(/Sorry, the file did not pass validation. Please review the validation errors in the report below/)) {
this.echo("Upload failed!", "ERROR");
errors = this.evaluate(function() {
var errorRows = __utils__.findAll({
type: 'xpath',
path: '//table[#id="uploadTable"]/tr[position()>1]'
});
return Array.prototype.forEach.call(errorRows, function(e) {
return e;
});
});
this.echo(JSON.stringify(errors));
} else {
this.echo("Upload successful", "INFO");
}
});
Any ideas?
While you probably have an XPath syntax error, you must know that you cannot return DOM elements from a closure passed to the evaluate() method; you have to convert your NodeList and HTMLelement instances to some native Javascript types, eg. Arrays, Objects, strings, etc…
Also, there's a convenient getElementsByXPath() method in the ClientUtils module you can use from the __utils__ instance automatically injected in every page your load:
casper.then(function() {
if (this.fetchText('.statusMessageContainer').match(/Sorry, the file did not pass validation. Please review the validation errors in the report below/)) {
this.echo("Upload failed!", "ERROR");
var errors = this.evaluate(function() {
var errorRows = __utils__.getElementsByXPath('//table[#id="uploadTable"]/tr[position()>1]');
return Array.prototype.map.call(errorRows, function(e) {
return e.innerText; // let's get node text instead of HTMLelement!
});
});
this.echo(JSON.stringify(errors));
} else {
this.echo("Upload successful", "INFO");
}
});
You can also use the ClientUtils bookmarklet to test your selectors right within your browser console as well. For example here, click the bookmarklet and execute this in the js console:
__utils__.getElementsByXPath('//table[#id="uploadTable"]/tr[position()>1]')
Then you'll see if your selector is correct (it works by my side — I mean it is syntactically correct).
Well from your error it appears there is something wrong with your selector.
It's setup correctly from what I can see, except for one thing: Try changing '//table[#id="uploadTable"]/tr[position()>1]' to '//table[#id='uploadTable']/tr[position()>1]' (change "" to '')
Other than that, your XPath looks syntactically correct, so I'm not sure why it would qualify as an invalid selector.

How know if ModelState contains errors

When a form is posted in my controller, I make the following check:
if(ModelState.IsValid)
If the model is not valid, errors are added to the ModelState. The model is then passed to the view with validation summary.
However, I want to check if the ModelState has errors from inside the jQuery ready handler, so that I can add some additional behavior if the form has errors. Is that possible?
You could spit global javascript variable:
<script type="text/javascript">
var isValid = #Html.Raw(Json.Encode(ViewData.ModelState.IsValid));
</script>
and then:
$(function() {
if (!isValid) {
alert('opa');
}
});
a little addition to #Dimitrov answer:
<script type="text/javascript">
var isValid = '#Html.Raw(Json.Encode(ViewData.ModelState.IsValid))';
if (isValid != 'true')
// model has some errors...
</script>
It's important to use single qoutes around the helper. Otherwise, that ending semicolon ; cause problems. Nether you can write it, nor you can't, at all cases it cause a syntax error. Unless you put those single quotes around the helper as I mentioned.
In addition to Darins Answer:
In .cshtml:
#Html.Hidden("IsValid", Json.Encode(ViewData.ModelState.IsValid))
in JS
var isValid = $('#IsValid').val().toLowerCase() == "true";

Having IE Issues When Passing Object By Ref. and Dynamically Adding Properties

So, I've created a function to do some error checking on an XML file that I recieve from an AJAX call. Part of the validation is that the function then builds out an object for easy access while I process that data into a form. In FF, works like a charm. IE dies with the error:
Object doesn't support this property or method
Here is the function (minus the un-important bits):
function checkReceiveXMLTagString( doc, messageObject, tag ) {
var tag_nodes = doc.getElementsByTagName( tag );
...do some error checking...
messageObject[tag] = tag_str; <-- error occurs on this line
return true;
}
Here is an example of how the function is call:
if ( checkReceiveXMLTagString( messageObject.Name[0], messageObject.Name[0], "First" ) ) {
...process messageObject.Name[0].First...
}
Like I said, FF has no issues. Safari loads the pages as well. IE has issues.
Thanks!
Looks like something is making messageObject be null or undefined
If the error is on this line:
messageObject[tag] = tag_str;
Then, the only two ways I know of that that can cause an error are:
messageObject is not an object that you can set properties on (null or undefined are the most likely ways that would happen)
tag is null or undefined
Since I see that your code calls this function hundreds of times so you can't effectively just break on it, I'd suggest you put in some defensive coding to check for those conditions and output something to the debug console to identify what the state is when the problem occurs. You can even trigger a conditional breakpoint with code like this:
if (!messageObject || !tag) {
debugger;
}
In the toughest cases, you can put an exception handler around it and break when the exception is thrown:
try {
messageObject[tag] = tag_str;
} catch(e) {
debugger;
}
Both of these will allow you to capture the condition in the debugger and examine all your parameters at the time of the error.

Page_ClientValidate is undefined in formview

I have validators inside a <asp:formview>, in order to show custom validation I am using
if (!Page_ClientValidate("groupName")) {}
I am getting an error Object Expected. How can I validate client side from the form view?
I use Page_ClientValidate for <asp:listview> and there
The Page_ClientValidate function may sometimes be undefined, e.g. if there are no validators on the page. Check if typeof Page_ClientValidate === "function" before calling it.
This would also occur if all validator's EnableClientScript properties are set to false.
Call the following Javascript function whenever you want and pass the validation group name of your form to it..
function ValidateForm(ValidationGroupName)
{
var validated=Page_ClientValidate(ValidationGroupName);
if(validated)
{
//do the logic here
return true;
}
else
{
return false;
}
}
Hope this will help you....

Categories