0

I have a form which has a select element, if the option 'Other' is selected a textarea will dropdown asking for extra information.

I want this textarea to be required unless the select option isn't 'Other'.

How would I go about doing this?

JavaScript (submitting the form to a controller)

var submitAnimatedForm = function (formHold, controllerURL, successMessage) {
    if (formHold.length) {
        var _form = formHold.find("form");

        _form.on("submit", function (e) {
            e.preventDefault();

            // Disables submit button on click
            $(':input[type=submit]').prop('disabled', true);

            // If the form is valid, post AJAX.
            if (_form.valid()) {
                setTimeout(function () {
                    $.ajax({
                        type: 'POST',
                        url: '/Umbraco/Surface/Contact/SubmitQuote',
                        data: _form.serialize(),
                        dataType: 'json',
                        encode: true,
                        success: function (data) {

                            if (!data.success) {
                                alert("ERR"); // - This is what I keep getting back
                            } else {
                                alert("SUCCESS");
                            }

                        },
                        error: function (data) {
                            console.log("ERR");
                        }
                    });
                }, 2000);
            }
        });
    }
};

C# (Checking the model data)

Controller:

if (!ModelState.IsValid)
{
    return Json (
        new
        {
            success = false,
            message = "Sorry, we encountered an error."
        }
    );
}

return Json (
    new
    {
        success = true,
        message = "Thank you, your request has been sent!"
    }
);

Model

public class ServiceModel
{
    [Required(ErrorMessage = "Your first name is required")]
    public String Firstname { get; set; }

    [Required(ErrorMessage = "Your last name is required")]
    public String Lastname { get; set; }

    [Required(ErrorMessage = "Your e-mail address is required")]
    [DataType(DataType.EmailAddress)]
    public String Email { get; set; }

    [Required(ErrorMessage = "Your job location is required")]
    public String Location { get; set; }

    [Required(ErrorMessage = "This field is required")]
    public String Service { get; set; }

    [Required(ErrorMessage = "Your job description is required")]
    public String Description { get; set; }

    public String EstimatedCost { get; set; }
}

I assume it's something to do with my C# code, I believe I could do a fix like so:

if (objModel.Service == "Other") 
{
    if (String.IsNullOrWhitespace(objModel.Description))
    {
        return Json (
            new
            {
                success = false,
                message = "Please fill out your description!"
            }
        )
    }
}
else
{
    // - Send an e-mail
}

But the issue with this is the fact that it's not checking the rest of the model and only the service description.

Any help would be appreciated! :)

Thanks

Halden Collier
  • 845
  • 7
  • 18
  • it looks like you are also using the valid jquery plugin, is it definitely passing the valid function and making the ajax request? What does your network inspector show? – tmkiernan Sep 18 '19 at 16:23

2 Answers2

1

I have two ideas you could go for in this case:

  1. Implement a custom jQuery validator to validate your textarea depending on the select element's value.

For this approach, check jQuery documentation for validator.addMethod and an example here


  1. Another approach would be to add an onChange function to the select element and make the textarea required depending on the value

For this approach, check this answer to check how to add the onChange function, and this answer to check how to set an element as required.


Update

Ok, after reading your question a second time, I believe you also want to validate your form on the server side. To do this, you could create a custom validation method and decorate your property with the method, like in this answer.

Grazina
  • 279
  • 4
  • 14
  • 1
    Thanks for the detailed answer, what I ended up doing was by using the reference you provided [here](https://stackoverflow.com/questions/17381043/how-to-dynamically-add-required-attribute-to-textarea-tag-using-jquery/17381051#17381051) and just added that `property` when it needed to be validated. – Halden Collier Sep 26 '19 at 15:24
1

You can create your own validation attribute to place on top of 'Description' property in your model.

You can learn about creating own validation attribute here.

And in the IsValid method of the custom validation attribute class, you can implement the logic to determine the success condition for the validation which will be something similar to what you have mentioned in your example.

akg179
  • 1,287
  • 1
  • 6
  • 14