javascriptc#asp.net-corerazor-pages

How to validate a form using Javascript


I'm trying to do a validation before submitting a from. I don't want to do it on model by putting those DataAnnotations So I have a form like this

<form id="MyForm" method="post" asp-page-handler="C#MethodForSaving" onsubmit="return validateForm(event)">
  <div class="form-group">
    <label asp-for="ModelExample.Name"></label>
    <textarea id="mytextarea" class="form-control" asp-for="ModelExample.Name" rows="10" placeholder="Enter Name"></textarea>
  </div>
  <div class="form-group">
    <label asp-for="ModelExample.Name2"></label>
    <textarea id="mytextarea" class="form-control" asp-for="ModelExample.Name2" rows="10" placeholder="Enter Name"></textarea>
  </div>
  <div class="form-group">
    <label asp-for="ModelExample.Name3"></label>
    <textarea id="mytextarea" class="form-control" asp-for="ModelExample.Name3" rows="10" placeholder="Enter Name"></textarea>
  </div>
  <button type="submit" class="btn btn-primary">Save</button>
</form>   

My JavaScript:

function validateForm(event) {
  const form    = document.getElementById('MyForm');
  let textAreas = form.querySelectorAll('textarea');
  let allFilled = true;
  
  for (let i = 0; i < textAreas.length; i++) {
    if (textAreas[i].value.trim() === "") {
      allFilled = false;
      break;
    }
  }

  if (!allFilled) {
    alert("All the Requirements are required.");
    event.preventDefault();  
    return false;
  }
  
  return true;
}

Now the problem that I have is that if the form comes with data inside and you try to clear one Text Area and try to click the save button it reloads the page and doesn't show the alert and all other passed ids when navigating to this page they get lost. What is it I might be doing wrong in terms of trying to validate those text fields when deleting input from one of those textarea and try to save and not get an alert but just reloads the page.


Solution

  • That's because when you click the button, it still goes to the OnPost you defined using asp-page-handler="C#MethodForSaving". My solution is add click event handler for the submit button.

    In the meantime, when you use asp-for="ModelExample.Name1" tag helper, it will automatically help generate a DOM with id="ModelExample_Name1" name="ModelExample_Name1".

    enter image description here

    You can try my codes.

    public class AboutModel : PageModel
    {
        [BindProperty]
        public Example ModelExample { get; set; } = default!;
        public void OnGet()
        {
        }
    
        public async Task<IActionResult> OnPostSavingAsync()
        {
            if (!ModelState.IsValid || ModelExample == null)
            {
                return Page();
            }
            return Page();
        }
    }
    
    public class Example
    {
        public string Description1 { get; set; }
        public string Description2 { get; set; }
        public string Description3 { get; set; }
    }
    
    @page
    @model WebAppNet8.Pages.AboutModel
    
    <form id="MyForm" method="post" asp-page-handler="Saving">
        <div class="form-group">
            <label asp-for="ModelExample.Description1"></label>
            <textarea class="form-control" asp-for="ModelExample.Description1" rows="10" placeholder="Enter Name"></textarea>
        </div>
        <div class="form-group">
            <label asp-for="ModelExample.Description2"></label>
            <textarea class="form-control" asp-for="ModelExample.Description2" rows="10" placeholder="Enter Name"></textarea>
        </div>
        <div class="form-group">
            <label asp-for="ModelExample.Description3"></label>
            <textarea class="form-control" asp-for="ModelExample.Description3" rows="10" placeholder="Enter Name"></textarea>
        </div>
        <button class="btn btn-primary" id="btn1">Save</button>
    </form> 
    
    @section Scripts{
        <script>
            $("#btn1").click(function (e) {
                alert(1);
                validateForm(e);
            });
    
            function validateForm(event) {
                const form = document.getElementById('MyForm');
                let textAreas = form.querySelectorAll('textarea');
                let allFilled = true;
                for (let i = 0; i < textAreas.length; i++) {
                    if (textAreas[i].value.trim() === "") {
                        allFilled = false;
                        break;
                    }
                }
                if (!allFilled) {
                    alert("All the Requirements are required.");
                    event.preventDefault();
                    return false;
                }
                return true;
            }
        </script>
    }