Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually set unobtrusive validation error on a textbox

I'm doing something similar to the remote validation, except that I already make my calls manually via jquery and setup whatever I had to setup.

Now my problem is, if I want to tell the validator that a particular textbox is not valid (and prevents the page from submitting, highlight the textbox, etc). How would I do this from code?

@Html.LabelFor(m => Model.Slug)
@Html.TextBoxFor(m => Model.Slug)
<span id="UrlMsg" class="field-validation-error" style="display: none;"></span>

 if (error) {
        $('#UrlMsg').html('This name is already in use.').fadeIn('fast');
        //what should I do here for the rest of the validation?
 }
like image 352
Shawn Mclean Avatar asked Sep 11 '11 18:09

Shawn Mclean


People also ask

How can I show error message below the textbox in jQuery validation?

Java scriptready(function() { $("#basic-form"). validate(); }); This is based on the assumption that you have already added the required JavaScript files. Adding those lines of JavaScript will make sure that your form is properly validated and shows all the error messages.

What is unobtrusive JavaScript validation?

Unobtrusive Validation means without writing a lot of validation code, you can perform simple client-side validation by adding the suitable attributes and including the suitable script files. These unobtrusive validation libraries need to be added: jquery.validate.min.js.

What does validator unobtrusive parse do?

validator. unobtrusive. parse(selector) method to force parsing. This method parses all the HTML elements in the specified selector and looks for input elements decorated with the [data-val=true] attribute value and enables validation according to the data-val-* attribute values.

What is unobtrusive validation in asp net?

Unobtrusive validation makes use of jQuery library and data-* attributes of HTML5 to validate data entered in the web form controls. Unobtrusive validations can be enabled in the web. config file, Global. asax or individual Web Form code-behind.


3 Answers

First, you can add a validation summary:

@Html.ValidationMessageFor(m => m.Slug) 

Then you can manually trigger jQuery validation / unobtrusive validation with the .showError method. Here is a sample:

var errorArray = {}; errorArray["Slug"] = 'Some error message for the Slug text box'; $('#SomeFormId').validate().showErrors(errorArray); 
like image 155
SkipHarris Avatar answered Sep 21 '22 17:09

SkipHarris


You can also do:

@Html.ValidationMessageFor(m => m.Slug) 

With this function in your code:

function setError(id, message) {         var span = $("span[data-valmsg-for=\"" + id + "\"]");         if (span && span.length > 0) {             $(span).html(message);             if (message && message != "") {                 $(span).removeClass("field-validation-valid");                 $(span).addClass("field-validation-no-valid");             } else {                 $(span).removeClass("field-validation-no-valid");                 $(span).addClass("field-validation-valid");             }         }     } 

Then can set the error

setError("Slug", "errorMsg"); 
like image 34
FRL Avatar answered Sep 23 '22 17:09

FRL


Using showErrors did not allow the error to persist, so that running .valid() cleared the error. Instead, I added a "forcibleerror" rule and a javascript method to set the message.

function forceError(element, errorMessage) {
    $(element).rules("add", {
        forcibleerror: true,
        messages: {
            forcibleerror: function () { return errorMessage; }
        }
    });
    var isForced = false;
    if (errorMessage) {
        isForced = true;
    }
    $(element)[0].dataset.isForced = isForced;
    $(element).valid();
}
$.validator.addMethod("forcibleerror", function (value, element) {
    return $(element)[0].dataset.isForced !== "true";
});

Usage:

forceError($('#Slug'), 'my custom message');

To put it back in a valid state:

forceError($('#Slug'), '');
like image 21
kevinpo Avatar answered Sep 21 '22 17:09

kevinpo