AlexGH AlexGH - 5 months ago 28
jQuery Question

Validate field in Razor View using JQuery

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");
}
})
})

Answer

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");
               }
           })