0

I have a controller action where I validate if any value is entered in fields or not. Here is how I do it:

[HttpPost]
        public ActionResult ValidateFields(string Desc, string Status, string Name )
        {
            string[] fields = new string[3];

            if (string.IsNullOrEmpty(Desc))
                fields[0] = "#Desc";

            if (string.IsNullOrEmpty(Status))
                fields[1] = "#Status";

            if (string.IsNullOrEmpty(Name))
                fields[2] = "#Name ";

// Check if the initialized array "fields" has any items in it.
            if (fields != null)
            { return content("Please enter valid values for " + fields); }

            return content("Validation Successful");
        }

Here array "fields" is initialized and hence its length is never 0. Also, checking for null does not work. All I can do i loop through the array and check if it has any items in it.

Is there a better way of checking if an array has any items in it or just null values?

Also, if there is any better way of validating fields than how I am doing, please let me know. I want it to be maintainable, if tomorrow I add new fields I want to spend as little time I can to validating them.

0

4 Answers 4

4

Why don't you use a List<string> instead? That will allow you to add each of the fields and then you could check the length of the list.

Sign up to request clarification or add additional context in comments.

Comments

2

Use lists.

    [HttpPost]
    public ActionResult ValidateFields(string Desc, string Status, string Name )
    {
        List<string> fields = new List<string>();

        if (string.IsNullOrEmpty(Desc))
            fields.Add("#Desc");

        if (string.IsNullOrEmpty(Status))
            fields.Add("#Status");

        if (string.IsNullOrEmpty(Name))
            fields.Add("#Name");

        // Check if the list "fields" has any items in it.
        if (fields.Any()) {
             return content("Please enter valid values for " + string.Join(", ", fields)); 
        }

        return content("Validation Successful");
    }

UPDATE

Another, probably better and more maintainable, way to validate is to create a model class, and add validation attributes. See here.

Comments

2

I believe you can do:

if (fields.Any(f => !string.IsNullOrEmpty(f)))

Comments

1

You can also do it for array. Just invoke:

fields.Any(i => i != null)

You can also improve your validation by using built-in ASP.NET MVC validation mechanism.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.