Checking if a ValidationGroup is valid from code-behind - asp.net

Is there a method I can call that retrieves a boolean value of whether or not a particular ValidationGroup is valid? I don't want to actually display the validation message or summary - I just want to know whether it is valid or not.
Something like:
Page.IsValid("MyValidationGroup")

Have you tried using the Page.Validate(string) method? Based on the documentation, it looks like it may be what you want.
Page.Validate("MyValidationGroup");
if (Page.IsValid)
{
// your code here.
}
Note that the validators on the control that also caused the postback will also fire. Snip from the MSDN article...
The Validate method validates the
specified validation group. After
calling the Validate method on a
validation group, the IsValid method
will return true only if both the
specified validation group and the
validation group of the control that
caused the page to be posted to the
server are valid.

protected bool IsGroupValid(string sValidationGroup)
{
foreach (BaseValidator validator in Page.Validators)
{
if (validator.ValidationGroup == sValidationGroup)
{
bool fValid = validator.IsValid;
if (fValid)
{
validator.Validate();
fValid = validator.IsValid;
validator.IsValid = true;
}
if (!fValid)
return false;
}
}
return true;
}

var isValidGroup = Page
.GetValidators(sValidationGroup)
.Cast<IValidator>()
.All(x => x.IsValid);

Try this:
Page.Validate("MyValidationGroup");
if (Page.IsValid)
{
//Continue with your logic
}
else
{
//Display errors, hide controls, etc.
}
Not exactly what you want, but hopefully close.

Page.IsValid will be false if any of the validated validation groups was invalid. If you want to validate a group and see the status, try:
protected bool IsGroupValid(string sValidationGroup)
{
Page.Validate(sValidationGroup);
foreach (BaseValidator validator in Page.GetValidators(sValidationGroup))
{
if (!validator.IsValid)
{
return false;
}
}
return true;
}

Pavel's answer works but isn't the simplest. Here is how I solved it:
protected Boolean validateGroup(String validationGroupName) {
Boolean isGroupValid = true;
foreach (BaseValidator validatorControl in Page.GetValidators(validationGroupName)) {
validatorControl.Validate();
if (!validatorControl.IsValid)
isGroupValid = false;
}
if (!isGroupValid)
return false;
else
return true;
}

Related

what is the best practice of Vert.x handler for checking check existence?

I am implementing a method using Vertx to check the existence of certain value in the database and use Handler with AsyncResult.
I would like to know which one is the best practice:
Option 1: When nothing found, Handler is with succeededFuture but with result as FALSE:
public void checkExistence (..., String itemToFind, Handler<AsyncResult<Boolean>> resultHandler) {
// ....
doQuery(..., queryHandler -> {
if (queryHandler.succeeded()) {
List<JsonObject> results = queryHandler.result();
boolean foundIt = false;
for (JsonObject json: results) {
if (json.getString("someKey").equals(itemToFind)) {
foundIt = true;
break;
}
}
resultHandler.handle(Future.succeededFuture(foundIt));
} else {
resultHandler.handle(Future.failedFuture(queryHandler.cause().toString()));
}
});
}
Option 2: When nothing found, Handler is with failedFuture:
public void checkExistence (..., String itemToFind, Handler<AsyncResult<Void>> resultHandler) {
// ....
doQuery(..., queryHandler -> {
if (queryHandler.succeeded()) {
List<JsonObject> results = queryHandler.result();
boolean foundIt = false;
for (JsonObject json: results) {
if (json.getString("someKey").equals(itemToFind)) {
foundIt = true;
break;
}
}
// HERE IS THE DIFFERENCE!!!
if (foundIt) {
resultHandler.handle(Future.succeededFuture());
} else {
resultHandler.handle(Future.failedFuture("Item " + itemToFind + " not found!"));
}
} else {
resultHandler.handle(Future.failedFuture(queryHandler.cause().toString()));
}
});
}
UPDATE:
Let's say I have another example, instead of checking the existence, I would like to get all the results. Do I check the Empty results? Do I treat Empty as failure or success?
Option 1: only output them when it's not null or empty, otherwise, fail it
public void getItems(..., String itemType, Handler<AsyncResult<List<Item>>> resultHandler) {
// ....
doQuery(..., queryHandler -> {
if (queryHandler.succeeded()) {
List<Item> items = queryHandler.result();
if (items != null && !items.empty()) {
resultHandler.handle(Future.succeededFuture(items));
} else {
resultHandler.handle(Future.failedFuture("No items found!"));
}
} else {
resultHandler.handle(Future.failedFuture(queryHandler.cause().toString()));
}
});
}
Option 2: output results I got, even though it could be empty or null
public void getItems(..., String itemType, Handler<AsyncResult<List<Item>>> resultHandler) {
// ....
doQuery(..., queryHandler -> {
if (queryHandler.succeeded()) {
List<Item> items = queryHandler.result();
resultHandler.handle(Future.succeededFuture(items));
} else {
resultHandler.handle(Future.failedFuture(queryHandler.cause().toString()));
}
});
}
The 1st one option is better, because you can clearly say, that checkExistence returned True or False and completed successfully or it failed with some exception (database issue, etc.).
But lets say, you've decided to stick with 2nd option. Then, imagine you have another method:
void getEntity(int id, Handler<AsyncResult<Entity>> resultHandler);
If entity with provided id doesn't exists, will you throw exception (using Future.failedFuture) or return null (using Future.succeededFuture)? I think, you should throw exception to make your methods logic similar to each other. But again, is that exceptional situation?
For case with returning list of entities you can just return empty list, if there are no entities. Same goes to single entity: it's better to return Optional<Entity> instead of Entity, because in this way you avoid NullPointerException and don't have nullable variables in the code. What's better: Optional<List<Entity>> or empty List<Entity>, it's open question.
Particularly if you're writing this as reusable code, then definitely go with your first option. This method is simply determining whether an item exists, and so should simply return whether it does or not. How is this particular method to know whether it's an error condition that the item doesn't exist?
Some caller might determine that it is indeed an error; it that's the case, then it will throw an appropriate exception if the Future returns with false. But another caller might simply need to know whether the item exists before proceeding; in that case, you'll find yourself using exception handling to compose your business logic.

Asp.Net validation check at client side

I am validating data at client side in asp.net validator by using following code snipet.
function ValidateData(){
if (!Page_ClientValidate("Validator1") || !Page_ClientValidate("Validator2")) {
return false;
}
else{
return true;
}
I called it on submit of button. But it showing validation messages of Validator1 group. Its not showing me validation messages of Validator2 group.
Just gone through :
see this link question , here its told - || operator short-circuits if the left condition is true.
Does a javascript if statement with multiple conditions test all of them?
If you want both , then cant you try like this :
function ValidateData(){
if (!Page_ClientValidate("Validator1"))
{
if (!Page_ClientValidate("Validator2"))
{
return false;
}
else
{
return false;
}
return false;
}
else
{
return true;
}
}
Just a random try , this code :)
Rigin

Enable/disable asp.net validator controls within a specific "ValidationGroup" with jQuery?

I know how to enable/disable individual validator controls on the client side using
ValidatorEnable(validator, false);
But how do you enable/disable all the validators within a ValidationGroup?
The validator properties aren't rendered as attributes unfortunately, so I don't know a good way to select them directly. You can try to iterate the Page_Validators array and filter out the ones you want to work with.
Try:
$.each(Page_Validators, function (index, validator){
if (validator.validationGroup == "your group here"){
ValidatorEnable(validator, false);
}
});
Check this blogpost explaining how with javascript. The main part of the code from the blog:
<script type="text/javascript">
function HasPageValidators()
{
var hasValidators = false;
try
{
if (Page_Validators.length > 0)
{
hasValidators = true;
}
}
catch (error)
{
}
return hasValidators;
}
function ValidationGroupEnable(validationGroupName, isEnable)
{
if (HasPageValidators())
{
for(i=0; i < Page_Validators.length; i++)
{
if (Page_Validators[i].validationGroup == validationGroupName)
{
ValidatorEnable(Page_Validators[i], isEnable);
}
}
}
}
</script>
Alternatively you can simply have ValidationGroup attribute with each validator defined .
Then you wont need any Jquery or javascript stuff to close them.
Here is the link that worked for me.
http://www.w3schools.com/aspnet/showasp.asp?filename=demo_prop_webcontrol_imagebutton_validationgroup

How to combine similar JavaScript methods to one

I have an ASP.NET code-behind page linking several checkboxes to JavaScript methods. I want to make only one JavaScript method to handle them all since they are the same logic, how would I do this?
Code behind page load:
checkBoxShowPrices.Attributes.Add("onclick", "return checkBoxShowPrices_click(event);");
checkBoxShowInventory.Attributes.Add("onclick", "return checkBoxShowInventory_click(event);");
ASPX page JavaScript; obviously they all do the same thing for their assigned checkbox, but I'm thinking this can be reduced to one method:
function checkBoxShowPrices_click(e) {
if (_hasChanged) {
confirm(
'All changes will be lost. Do you wish to continue?',
function(arg) {
if (arg.toUpperCase() == 'YES') {
var checkBox = document.getElementById('<%=checkBoxShowPrices.UniqueID%
>');
checkBox.checked = !checkBox.checked;
eval("<%=base.GetPostBackEventReference(checkBoxShowPrices)%>");
_hasChanged = false;
}
});
return false;
} else {
eval("<%=base.GetPostBackEventReference(checkBoxShowPrices)%>");
}
}
function checkBoxShowInventory_click(e) {
if (_hasChanged) {
confirm(
'All changes will be lost. Do you wish to continue?',
function(arg) {
if (arg.toUpperCase() == 'YES') {
var checkBox = document.getElementById('<%
=checkBoxShowInventory.UniqueID%>');
checkBox.checked = !checkBox.checked;
eval("<%=base.GetPostBackEventReference(checkBoxShowInventory)%>");
_hasChanged = false;
}
});
return false;
} else {
eval("<%=base.GetPostBackEventReference(checkBoxShowInventory)%>");
}
}
Add to the event the checkbox that is raising it:
checkBoxShoPrices.Attributes.Add("onclick", "return checkBox_click(this, event);");
Afterwards in the function you declare it like this:
function checkBoxShowPrices_click(checkbox, e){ ...}
and you have in checkbox the instance you need
You can always write a function that returns a function:
function genF(x, y) {
return function(z) { return x+y*z; };
};
var f1 = genF(1,2);
var f2 = genF(2,3);
f1(5);
f2(5);
That might help in your case, I think. (Your code-paste is hard to read..)

Dropdownlist doesn't postback after Page_ClientValidate()

Update:
I have just found the solution. The following function works (remove the else part):
function confirmSubmit() {
if (Page_ClientValidate("Group1")) {
return window.confirm("Are you sure to submit the form?");
}
}
But I am wondering why it doesn't work when I add the else part.
Question:
I want to have a confirm dialog after user fills in all the data in the form.
I set onclientclick="return confirmSubmit()" in the submit button.
function confirmSubmit() {
if (Page_ClientValidate("Group1")) {
return window.confirm("Are you sure to submit the form?");
} else {
return false;
}
}
If Page_ClientValidate("Group1") returns false, the dropdownlist doesn't cause postback after I first select the item, and the postback only occurs when I select the dropdownlist second time.
What's the problem?
After Page_ClientValidate is called, the variable Page_BlockSubmit gets set to true, which blocks the autopost back. Page_BlockSubmit was getting reset to false on the second click, for what reasons I still don't fully understand. I'm looking more into this, but I have a solution and I'm under the gun so I'm rolling with it....
Just add below code in the code block which executes if Page is not valid.
Page_BlockSubmit = false;
e.g.
function ValidatePage()
{
flag = true;
if (typeof (Page_ClientValidate) == 'function')
{
Page_ClientValidate();
}
if (!Page_IsValid)
{
alert('All the * marked fields are mandatory.');
flag = false;
Page_BlockSubmit = false;
}
else
{
flag = confirm('Are you sure you have filled the form completely? Click OK to confirm or CANCEL to edit this form.');
}
return flag;
}
I have just found the solution. The following function works (remove the else part):
function confirmSubmit() {
if (Page_ClientValidate("Group1")) {
return window.confirm("Are you sure to submit the form?");
}
}

Resources