Search code examples
javascriptjquerymaterialize

Trigger input validation error with JQuery on materialize?


I know it's a pretty lame question, but I couldn't find it in documentation and neither around forums.

I have this HTML

<div class="input-field col s3">
    <label for="CEP">CEP <span class="mandatory">*</span></label>
    <input class="validate" id="CEP" name="CEP" required="required" type="text" />
</div>

I don't have a form for this field because I will post it via ajax. Before I send I want to check if it have a value, so I will do something like this

if($("#CEP").val() === '')
{
    //trigger error and return
}

The problem is: I want to trigger the validation error correct using JQuery. but I don't know how.

Thanks in advance.


Solution

  • It's very simple. Just try:

    ...

    if($("#CEP").val() === '')
    {
        $('#CEP').addClass('invalid');
    }
    

    And also add the error message on the input when the validation is wrong:

    <div class="input-field col s3">
        <label for="CEP">CEP <span class="mandatory">*</span></label>
        <input class="validate" id="CEP" name="CEP" required="required" type="text" />
        <span class="helper-text" data-error="Wrong Credentials!"></span>
    </div>