Developer forum

Forum » Development » Throw validation error on OnAfterSubmitSave

Throw validation error on OnAfterSubmitSave

Martin Moen
Reply

Is it possible to use Dynamicweb.Forms.Notifications.Frontend.OnAfterSubmitSave to make custom server side validation?
I would like to validate one of the fields up against the database on submit. If invalid, I need to show a error message.

Anyone got any examples?


Replies

 
Nicolai Pedersen Dynamicweb Employee
Nicolai Pedersen
Reply

Hi Martin

That would be too late in the process as the submit has already been added to DB.

You can use Notifications.Frontend.OnBeforeContent:

using Dynamicweb.Extensibility.Notifications;
using Dynamicweb.Notifications;
using System;

namespace Dynamicweb.Examples.Notifications
{
    [Subscribe(Dynamicweb.Forms.Notifications.Frontend.OnBeforeContent)]
    public class FormSubscriber : NotificationSubscriber
    {
        public override void OnNotify(string notification, NotificationArgs args)
        {
            if (args == null)
                return;

            var loadedArgs = (Dynamicweb.Forms.Notifications.Frontend.OnBeforeContentArgs)args;

            if (loadedArgs != null && loadedArgs.ContentModule.RequestContext("cmd").Equals("save", StringComparison.OrdinalIgnoreCase))
            {
                bool submitNotAllowed = false;
                //Logic to test what is being submitted
                //submitNotAllowed=true
                if (submitNotAllowed)
                {
                    loadedArgs.StopExecution = true;
                    loadedArgs.Output = "<h1>Not allowed</h1>";
                }
            }
        }
    }
}
 
Martin Moen
Reply

Thanks! Looks like it is working, but not completly as expected.

loadedArgs.Output = "<h1>Not allowed</h1>";

This line replace the form with "Not allowed". Is it possible to just add the text above the form. So that the user still can make changes to the form without reloading the whole page?

 
Nicolai Pedersen Dynamicweb Employee
Nicolai Pedersen
Reply
This post has been marked as an answer

Not as it is now.

loadedArgs.StopExecution = true;

Make the form not render. But why not add validation in the form it self - client side. If someone then manipulates the submit, they can handle this kind of error.

Alternatively you can return a script:

loadedArgs.Output = "<script>alert('Not allowed');history.go(-1);</script>";

Votes for this answer: 1

 

You must be logged in to post in the forum