0

I have a simple javascript file that just needs to run the rules method. Unfortunately, it is not working for some reason. I know my custom javascript file is being rendered fine as the input masking is working fine. I have double checked to make sure I have the jquery validate script being rendered, so I am unsure as to what my problem is. The project is a simple mvc website written on a Visual Studio Enterprise 2015 platform. The page in question on the website is the EditInfo page, for your reference.

Here is the BundleConfig.cs adding the validate bundle.

public static void RegisterBundles(BundleCollection bundles)
    {
     //More bundles obviously are added
      bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*"));
    }

Next, here is the Layout file, where the script is rendered.

@Scripts.Render("~/bundles/jqueryval")

Next, here are the 2 custom javascript files declared in the view.

    <script src="@Url.Content("~/Scripts/EditInfo.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/app.js")" type="text/javascript"></script>

Then, here is the EditInfo custom javascript file that uses the validate method. This is the whole file, minus the 3 lines regarding input masking that work fine.

$(document).ready(function () {
var counter = 0;
var $CreateProfilevalidator = {};


$CreateProfilevalidator = $("#frmEditInfo").validate({
    rules: {
        personalEmail:/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,15}|[0-9]{1,3})(\]?)$/i,
        otherEmail: /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,15}|[0-9]{1,3})(\]?)$/i,
        workCell: /^\(?\d{3}\)?\s?-?\d{3}\s?-?\d{4}$/,
        personalCell: /^\(?\d{3}\)?\s?-?\d{3}\s?-?\d{4}$/,
        otherPhone: /^\(?\d{3}\)?\s?-?\d{3}\s?-?\d{4}$/
    },
    messages: {
        personalEmail: "Invalid Email",
        otherEmail: "Invalid Email",
        workCell: "Invalid Phone Number",
        personalCell: "Invalid Phone Number",
        otherPhone: "Invalid Phone Number"
    },
    errorPlacement: function (error, element) {
        errorPlacementValidator(error, element);
    },
    highlight: function (element, errorClass, validClass) {
        counter++;
        highlightValidator(element, errorClass, validClass, counter);
    },
    unhighlight: function (element, errorClass, validClass) {
        counter++;
        unhighlightValidator(element, errorClass, validClass, counter);
    }

});
});

Finally, here is the app.js file that contains the 3 validator methods used in my javascript file.

function errorPlacementValidator(error, element) {
if (element.is(":radio")) {
    error.appendTo(element.closest("[class*='col-sm-']"));
}
else if (element.parents('.selectric-wrapper').size() > 0) {
    console.log('selectric error');
    error.appendTo(element.closest('[class*="col-sm-"]'));
}
else {
    error.appendTo(element.parent());
}
}

function highlightValidator(element, errorClass, validClass, counter) {
var $parent = $(element).parent();

// remove icon and success spans if any
$parent.find("span.form-control-feedback, span.sr-only").remove();

// add ".error" class to input element
$(element).addClass(errorClass).removeClass(validClass);

// add Bootstrap ".has-error" class to parent div.form-group element
$(element).closest(".form-group").removeClass("has-success").addClass("has-error has-feedback");

// need to have it check to see if span already added
// only add for non radio or non select input elements
if (!$(element).is(":radio, select, textarea, :checkbox, .btn") && !$(element).hasClass("datepicker")) {
    counter++;

    var $spans = $parent.find("span");

    // check to make sure error spans are not already in form-group before attempting to append after input
    if ($spans.length == 0) {
        // add span element with ".glyphicon" ".glyphicon-remove" ".form-control-feedback" classes after input
        $(element).after("<span class='glyphicon glyphicon-remove form-control-feedback' aria-hidden='true'></span>");
        $(element).after("<span id='inputError" + counter + "Status'" + " class='sr-only'>(error)</span>");
    }
}
}

function unhighlightValidator(element, errorClass, validClass, counter) {
var $parent = $(element).parent();

// remove icon and success spans if any
$parent.find("span.form-control-feedback, span.sr-only").remove();

// remove ".error" class from input element
$(element).removeClass(errorClass).addClass(validClass);

if (!$(element).is(":radio, select, textarea, :checkbox, .btn") && !$(element).hasClass("datepicker")) {
    // // remove Bootstrap ".has-error" class from parent div.form-group element
    $(element).closest(".form-group").removeClass("has-error").addClass("has-success has-feedback");

    var $spans = $parent.find("span");

    if ($spans.length == 0 && !$(element).is("select")) {
        $(element).after("<span class='glyphicon glyphicon-ok form-control-feedback' aria-hidden='true'></span>");
        $(element).after("<span id='inputSuccess" + counter + "Status'" + " class='sr-only'>(error)</span>");
    }
} else if ($(element).parents('.selectric-wrapper').size() > 0) {
    $(element).closest(".form-group").removeClass("has-error").addClass("has-success has-feedback");
}
}

I have googled and done my research, but the cause still escapes my grasp. If I have left out any important information, I apologize. But the site I am writing still will not give an error when I put an improperly formatted email address or shorter than required phone number. Edit: wording

3
  • Have you tried reading the documentation or looking at other examples here on SO? I can tell you that I’ve never seen an attempt like this. Commented Apr 16, 2018 at 14:45
  • @Sparky What do mean 'attempt like this'? What is abnormal about my attempt? (no sass meant) I had thought I was following the usual procedure. Commented Apr 16, 2018 at 14:47
  • You're totally missing the rules themselves. See answer below. Commented Apr 16, 2018 at 15:05

1 Answer 1

1

The rules object is constructed using a comma-separated list of key: value pairs that represent field names with their methods. Inside of the methods part is another comma-separated list of key: value pairs that represent the method name and its parameter. Your attempt is totally missing the actual rules (methods).

$('#yourform').validate({
    rules: {  
        fieldname1: {        // <- field NAME
            required: true,  // <- rule (method) : parameter
            phoneUS: true    // <- rule (method) : parameter
        },
        fieldname2: {        // <- field NAME
            required: true,  // <- rule (method) : parameter
            email: true      // <- rule (method) : parameter
            .....

If you want to validate regex, then you need to use the pattern method that is part of the additional-methods.js file.

$CreateProfilevalidator = $("#frmEditInfo").validate({
    rules: {
        personalEmail: {
            pattern: /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,15}|[0-9]{1,3})(\]?)$/i
        },
        otherEmail: {
            pattern: /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,15}|[0-9]{1,3})(\]?)$/i
        } 
        ....

Since your list of rules is missing, I also have no idea if you want the field required, etc. But you'd need to list those rules as well.

While we're at it, why all the regex? The plugin already includes various methods for phone numbers and email addresses. Refer to the docs and browse the Additional-Methods file.

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

5 Comments

I didn't realize that to use regex, the pattern method was required, thank you. And the no {} for each rule was me throwing stuff at the wall and hoping something stuck. I had it the correct way earlier. Is the additional-methods.js file automatically rendered in the validate bundle? Or do I need to declare that specific script file myself? Final question, do I need the 'required: true'? I don't need them to be required, it's an internal site (in the U.S.) and the regex and input masking should keep the phone numbers at the appropriate length.
This answer is not specific to ASP, which is something you never mentioned in the question either. However, I imagine that you'll need to include the additional-methods.js separately. Otherwise, copy the method out of this file and paste it into your own JavaScript someplace.
required rule has nothing to do with length. It simply makes the field mandatory to fill out. If it's not mandatory, then you don't need it. However, IMO, just use the phone and email rules built into the plugin.
Thank you. And I apologize, I forgot to include ASP.Net in the header. Yes, I am using ASP.Net.
My bad on wording, I meant I didn't need a length rule, but didn't clarify. Thanks again for your help.

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.