1

I want to have a script to validate if a field called Email is not empty. I created a script which I put in the SCRIPTS folder. But nothing is fired when we click the Create button. Any idea of what is wrong with this ? Thanks

ValidationEmail.js

     $(function () {
        $("SubmitBTNCreate").click, function (e) {
           var email = $("#Email").val();
           if (email == "")  {
               e.preventDefault();
               alert("Please enter an email address.");
           }
        });
     });

Create.cshmtl

 @model codefirst.Models.Personne

 @{
    ViewBag.Title = "Create";
 }



 <h2>Create</h2>

 @using (Html.BeginForm()) {
 @Html.AntiForgeryToken()
 @Html.ValidationSummary(true)

 <fieldset>
    <legend>Personne</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Nom)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Nom)
        @Html.ValidationMessageFor(model => model.Nom)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Prenom)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Prenom)
        @Html.ValidationMessageFor(model => model.Prenom)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Email)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Email)
        @Html.ValidationMessageFor(model => model.Email)   <== field to check if empty
    </div>

    <p>
       <input type="submit" value="Create" id="SubmitBTNCreate" />  <== btn submit
     </p>
 </fieldset>
 }

 <div>
    @Html.ActionLink("Back to List", "Index")
 </div>

 @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/Scripts/ValidationEmail")   <== calling the script

}

4
  • What version your jquery is? Open console and write $.fn.jquery to see. Other than that, see the generated html and check if the input has REALLY id Email, because I remember working on a project which added some names to the id so the $('#Email') would not work. Commented Mar 11, 2014 at 13:27
  • Also you are expecting something wrong. @Html.ValidationMessageFor(model => model.Email) <== field to check if empty if I remember right, ValidationMessageFor is not an input, it's a div with errors (if any). If you really want to test the div, change the .val() from the answers to var email = $("#Email").empty() or var email = $("#Email").html() === '' to return true or false Commented Mar 11, 2014 at 13:30
  • Jquery version is 1.8.2 I found a error 404 Not found url: localhost:50821/Scripts/ValidationEmail in the Scripts folder I got ValidationEmail.js Commented Mar 11, 2014 at 13:42
  • tried @Scripts.Render("~/Scripts/ValidationEmail.js") instead? I don't have VS at work so can't test that atm. Anyways, now you know that your code does not work because you are not loading the script. Commented Mar 11, 2014 at 14:11

5 Answers 5

1

Your code has syntax errors, missing # and click binding is wrong:

$("SubmitBTNCreate").click, function (e) {

I would rewrite it as this:

$(function () {
   $("#SubmitBTNCreate").click(function(e) {
      // use preventDefault() at top
      e.preventDefault();
      var email = $("#Email").val();
      // asking with shorter format works and looks better
      if (!email)  {
         alert("Please enter an email address.");
         return false;
      }
      // no errors, submit form by id you give it
      $("#yourFormId").submit();
   });
});

Edit:

Problem with include might get solved by including it this way:

<script src="@Url.Content("~/Scripts/ValidationEmail.js")"></script>
Sign up to request clarification or add additional context in comments.

5 Comments

Interesting, this fixes javascript bugs though. I assume that jQuery is correctly loaded if you view network tab and no errors at javascript console? if there is, would like to see them updated to question.
V I check the Network (I am using Chrome Pf12). I can't see the script been called ValidationEmail. Should I see it there ? I see jquery-1.8.2.js. browserLink, negociate?requestURL, etc
On page load you should see at least jquery and your ValidationEmail.js (or whatever it names is) - if you dont see the latter, there is no way that validation nor click could work. :)
I got a page 404 not found url localhost:50821/Scripts/ValidationEmail but the scripts is under the project folder Scripts with the name of ValidationEmail.js
so the problem is that it is not a bundle and you are including it as bundle format? :) progress! does this help for include? stackoverflow.com/questions/19012190/…
0

Use this, You are missing # in ID selector and you are missing binding the event

 $(function () {
        $("#SubmitBTNCreate").bind('click', function (e) {
           var email = $("#Email").val();
           if (email == "")  {
               e.preventDefault();
               alert("Please enter an email address.");
           }
        });
     });

Comments

0

I would give your form an ID in the @using (Html.BeginForm()) as in order to do any validation, you need to prevent the form from submitting on the button click. So what'd you'd want is something along the lines of @using (Html.BeginForm(new { id = "emailForm" })). This will allow you to reference it from your javascript.

With that in place, you'll be able to fix your bugs in your javascript function.

$(document).ready(function() {
    // You're missing the # to tell jQuery you're looking by ID
    // You also had a ',' instead of a '('
    $("#SubmitBTNCreate").click( function (e) {
        // The very first thing you need to do is prevent the default 
        // because it will fire off asynchronously.
        if (e.preventDefault) {
            e.preventDefault();
        }
        // Also allow for IE8
        else {
            e.returnValue = false;
        }

        var email = $("#Email").val();
        if (email == "")  {
            alert("Please enter an email address.");
        }
        else {
            // If you have no validation errors, submit the form.
            $("#emailForm").submit();
        }
    });
});

2 Comments

I tried this but the screen is not returning anything when I click Create the url is /Home/Create/emailform
Try filling out the other parameters in the BeginForm method. The overload I typically use is BeginForm(*action*, *controller*, FormMethod.Post, new { id = "emailForm"}). So you would replace action with "Create", and controller with "Home". That should be what you need.
0

The following line needs fixing:

$("#SubmitBTNCreate").on("click", function (e) {
// ^id selector       ^ use on() to bind event listener

Full code

   $(function () {
        $("#SubmitBTNCreate").on("click", function (e) {
           var email = $("#Email").val();
           if (email == "")  {
               e.preventDefault();
               alert("Please enter an email address.");
           }
        });
     });

DEMO

1 Comment

not working also.... It should be so easy this... I tried your demo and I agree it is working. But I guess with Razor something is different
0

I finally found the problem with your help.

in the Create.cshtml I added the .js to the script name

 @Scripts.Render("~/Scripts/ValidationEmail.js")

In the script I was missing the "#" in front of #SubmitBTNCreate

Validation.js

  $(function () {
     $("#SubmitBTNCreate").on("click", function (e) {
       var email = $("#Email").val();
       if (email == "") {
           e.preventDefault();
           alert("Please enter an email address.");
       }
     });
  });

or this also work

      $(function () {
     $("#SubmitBTNCreate").click ( function (e) {
       var email = $("#Email").val();
       if (email == "") {
           e.preventDefault();
           alert("Please enter an email address.");
       }
     });
  });

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.