1

I'm trying to use custom JQuery validation for a field inside a Razor view, but I don't know how to associate the field with the JQuery function, I've worked with JQuery but from html pages and forms, not using HtmlHelpers from Razor Views This is the field I want to validate(I'm referencing in the same page the JQuery .js that I need to)

  @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

I've tried to put an id inside it and change EditorFor to TextBoxFor and then call it from my JQuery function but it was unsuccessfull

  @Html.TextBoxFor(model => model.Name, new { id="artistName", htmlAttributes = new { @class = "form-control" } })

And this is the function I'm using in JQuery but I can't find how to bind it to the Html Helper:

$(document).ready(function () {
    $("#artistName").on("blur",function(){
        if ($(this).val().match('^[a-zA-Z]{3,16}$')) {
            alert("Valid name");
        }
        else {
            alert("That's not a name");
        }
    })
})
AlexGH
  • 2,735
  • 5
  • 43
  • 76

2 Answers2

1

Remove the id attribute and use $("#Name") as a selector.

@Html.TextBoxFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

           $("#Name").on("blur",function(){
               if ($(this).val().match('^[a-zA-Z]{3,16}$')) {
                   alert("Valid name");
               }
               else {
                   alert("That's not a name");
               }
           })
Carlos Figueroa
  • 1,743
  • 2
  • 14
  • 15
  • There should be something wrong because it's not working, I can enter anything inside the Textbox and is send to the database without problem – AlexGH Jun 08 '16 at 15:29
  • Another idea. Instead of having this validation code on the blur event of the textbox, you could also put it in the click event of the submit button. – Carlos Figueroa Jun 08 '16 at 15:32
  • using the submit button it worked good I don't know what's happening with the blur event on the TextboxFor field, I'd prefer to use the blur event to have instantly validation... I'll try to find out – AlexGH Jun 08 '16 at 16:05
  • I don't know what happened I guessed I updated the webpage incorrectly but it works now just like that!!! – AlexGH Jun 08 '16 at 16:33
0

Is it absolutely necessary that you use Javascript to validate ? The fields can be validated using Data annotations. Please look into this DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view

If you absolutely need to use jquery, then look into Jquery validation plugin. https://jqueryvalidation.org/documentation/

Community
  • 1
  • 1
Ranjan
  • 31
  • 2
  • Yes, I've validated already using Data Annotations but I want to find out how I can validate a field using custom JQuery without using a plugin – AlexGH Jun 08 '16 at 15:16