0

How to catch and show custom error message from the server side on the html page?

function getAlertMessage() {
    $.ajax({
        type : "POST",
        url : "getAlert.do",
        success : function(data) {
            data.alertmsg //How to set this msg to validatename property  in messages Attribute
        },
        error : function() {
            alert("No Court No details found");
        }
    });
}

$(document).ready(function() {
   $("#register-form").validate({
       rules : {
        username : {
          required : true,
          validname : true,
          minlength : 4
         }
        },
       messages : {
        username : {
         required : "Please Enter UserName",
         validname : getAlertMessage(), //it does not worked here
         minlength : "UserName is Too Short"}},
         errorPlacement : function(error,element) {
           $(element).closest('.form-group').find('.help-block').html(
error.html());
},
         highlight : function(element) {
         $(element).closest('.form-group')
         .removeClass('has-success')
         .addClass('has-error');
          },
         unhighlight : function(element,
         errorClass, validClass) {
         $(element).closest('.form-group')
         .removeClass('has-error')
         .addClass('has-success');
         $(element).closest('.form-group')
        .find('.help-block').html('');},
          submitHandler : function(form) {
           form.submit();}});});
2
  • You either call validate inside the success handler, or you change that setting in the success handler by accessing $("#register-form").validate().settings Commented Oct 13, 2016 at 14:16
  • Can you show me in Jsfiddle please ? Commented Oct 13, 2016 at 14:24

2 Answers 2

2

I've been working on this kind of issue and finally got it working. There is nothing similar online and this feels like a good place to put it as it directly relates to the question asked.

So what I needed was a server side function to do a check and decide what error message to return based on checking a database (a bit like a cms). This message needed to be displayed to the user and validate the field accordingly.

It might not be the best/cleanest way but it works and I don't think it's that bad! Basically, there needs to be a hidden field on the page to store the error message. So here's how I got it to work:

jQuery.validator.unobtrusive.adapters.add("customValidation", [], function (options) {
    options.rules["remote"] = {
        url: "/api/CustomValidation",
        type: "post",
        data: {
            fieldValue: function () { return options.element.value; }
        },
        beforeSend : function () {
            // Show loading gif
            $('#loader').show();
        },
        dataFilter: function (data) {
            // if the API returns a JSON string then this is needed
            var result = JSON.parse(data);

            if (result != undefined && result != null) {
                if (result.ErrorMessage != null) {
                    // update a hidden field on the page with the message.
                    $('#HdnValidationMessage').val(result.ErrorMessage);

                    // Field is not valid so return false
                    return false;
                }
                else {
                    // no error message returned so field must be valid
                    return true;
                }
            }
            else {
                // Something has gone wrong! I won't let this stop the user.
                return true;
            }
        },
        complete: function () {
            // hide loading gif
            $('#loader').hide();
        }
    };

    // Default error message set to fetch the error fromt he hidden field.
    options.messages["remote"] = function() { return $('#HdnValidationMessage').val(); }
});

Hope it helps someone who was stuck for a while on this like I was!

UPDATE:

Got this working without a hidden field. Not sure why I couldn't before but now it's much more straight forward.

So now the controller action server-side returns true if valid and an error message if incorrect. the below will display the error message:

 jQuery.validator.unobtrusive.adapters.add("customValidation", [], function (options) {
    options.rules["remote"] = {
        url: "/api/CustomValidation",
        type: "post",
        data: {
            fieldValue: function () { return options.element.value; }
        },
        beforeSend : function () {
            // Show loading gif
            $('#loader').show();
            $(options.element).prop("readonly", "readonly");
        },
        complete: function () {
            // hide loading gif
            $('#loader').hide();
            $(options.element).removeProp("readonly");
        }
    };
});
Sign up to request clarification or add additional context in comments.

Comments

1

Why would you need to do this when a remote method already exists?

Since this seems like nothing more than a server call to validate the username field, use the method designed for this purpose. From the server, send back true, false, or a JSON encoded string that represents a dynamic custom validation message.

The value of the field being validated by remote is already sent by default, so you'd only need to define the url and type parameters.

$(document).ready(function() {
    $("#register-form").validate({
        rules: {
            username: {
                required: true,
                minlength: 4,
                remote: {
                    url: 'getAlert.do',
                    type: 'POST'
                }
            }
        },
        messages: {
            username: {
                required: "Please Enter UserName",
                minlength: "UserName is Too Short"
                // DO NOT NEED 'remote' message since it's already coming from server
            }
        }, .....

That's all you'd need to define within rules and messages. The value of username is sent to your getAlert.do function on the server.

Then from your server, getAlert.do would need to send back a true if you want validation to pass, and a JSON encoded string representing the error message when you want validation to fail.

See: jqueryvalidation.org/remote-method/

1 Comment

getAlert.do will return an array of json objects.How do i check the condition and its respective message?

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.