Pregunta

I'm having a little trouble using knockout.validation. I've currently got a user interface that looks a little like this:

enter image description here

The problem I've got is that the icons don't seem to disappear, even if there are no errors as reported by viewModel.errors().length, however the text does.

enter image description here

I'm using a custom template for my error, defined in JavaScript like so:

   // Setup knockout-validation
    ko.validation.rules.pattern.message = 'Invalid.';
    ko.validation.configure({
        registerExtenders: true,
        messagesOnModified: false,
        insertMessages: true,
        parseInputAttributes: true,
        messageTemplate: 'errorMessage'
    });

    /// extend objects
    viewModel.errors = ko.validation.group(viewModel);

My error template is like so:

<!--This is the template for an error message that will be used by ko.validation - it should display an icon followed by the error message-->
<script id="errorMessage" type="text/html">
    <div class="validationMessage">
        <i class="fa fa-exclamation-triangle"></i><em class="customMessage" data-bind='validationMessage: field'></em>
    </div>
</script>

I actually just removed from a data-bind from the <i> which has data-bind="visible: field" as this didn't seem to be working properly. I'm also not entirely sure where field comes from - it may be a ko.validation property that I've forgotten. It meant the icon displayed still even when there was no error, but prevent the icon displaying when the field was empty so I had a "This field is required" message with no icon.

My validation object which gets extended to my observable looks like:

validation : { required: true, number: true }

A look at my viewModel during execution:

enter image description here

Can anyone suggest what I might be doing wrong to prevent these icons disappearing? I could manually remove them using jQuery but I'm hesitant to do so without fully understanding the problem.

¿Fue útil?

Solución

I've actually managed to find the resolution to this via a fiddle I stumbled across. The data-bind="visible: field" bit that I took out is the all important aspect. It seems field is the knockout validation item in context (which is why I couldn't figure out where it came from).

Binding directly to field however is wrong, this is simply binding to the value of the field which explains why it's alway there unless you provide an empty value. Knockout validation however has extended the object to include some additional functions. Specifically field.isValid() is the important call and can be used in the binding instead.

data-bind="visible: field.isValid()"
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top