0

I am developing a project in MVC 5. There is are some form input field where I need to put custom client side validation using jquery/javascript. The expected behaviour is for example when someone tries to type alphabets or special characters in the phone input, there should be a validation error displayed below the field or atleast an alert box should get triggered containing the error. I have added the custom validation file in my scripts folder. I can see some basic logs I wrote on the console of the page. I am facing challenges on the js function where we can capture the id of the field and provide custom logic for it. Here is my code. Please suggest what can be done.

@model StudentMVCApp.Models.registration

@{
    ViewBag.Title = "Create";
}


<h2>Create</h2>


@using (Html.BeginForm(new
{
    @id = "registerFormId",
    @class = "form-horizontal",
    role = "form" 
}))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Register a new student</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.firstname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.firstname, new { htmlAttributes = new { @class = "form-control", data_val = "true", data_val_required = "Please dont provide empty name!" } })
                @Html.ValidationMessageFor(model => model.firstname, "", new { @class = "text-danger" })
            </div>
            
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.lastname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.lastname, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.lastname, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.phone, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.phone, new { htmlAttributes = new { @class = "form-control",@id="phoneid" } })
                @Html.ValidationMessageFor(model => model.phone, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.email, "", new { @class = "text-danger" })
            </div>
        </div>


        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>

    </div>


}

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


@section Scripts {
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/Unobtrusive")
    @Scripts.Render("~/CustomValidation")
}

Here is my Custom JavaScript

console.log("I am working JS");
(function ($) {
    console.log("This function is captured");
    var phone = $("#phoneid").val();
    console.log(phone);
    if (phone != null)
        console.log(phone);
    else if (phone == 100)
        alert($(this).val());
    else if (phone == "abc")
        alert(phone);
    else if (phone == abc)
        alert(phone)
})(jQuery);


I tried different tutorials and experimented with some js functions. But couldn't get it working using id of the field.

0

2 Answers 2

1

I would recommend using jquery.validation.unobstrusive package scripts on your view:

<script src="~/Scripts/Jquery/jquery-1.9.1.js"></script>
<script src="~/Scripts/Jquery/jquery.validate.js"></script>
<script src="~/Scripts/Jquery/jquery.validate.unobtrusive.js"></script>

and adding your own custom validation on a form element by writing jquery such as:

$("#myinput").rules("add", {
  required: true,
  minlength: 2,
  messages: {
    required: "Required input",
    minlength: jQuery.validator.format("Field needs to be more than{0}")
  }
});

More info can be found at https://jqueryvalidation.org/rules/

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

Comments

0

You need to attach your code above to an event, input or submit for example. Now it only runs once, when the page loads

something like

$(function() {
  console.log("This function is captured");
  const $phone = $('#phoneid');
  $phone.on('input',function() {
    const val = $(this).val(); // get the value - it is a string
    console.log(val);
    if (val == 100) console.log('100'); // note the == coerces the numeric string to number
    else if (phone == 'abc') console.log('abc');
  });
});

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.