Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate Materializecss radio buttons?

I tried to implement validation to display an error message on radio button but I couldn't succeed.

I'm using Materializecss framework.

The validation/displaying error message works on text box element and not in radio button.

Code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <!-- Compiled and minified CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css">

  <!-- Compiled and minified JavaScript -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/js/materialize.min.js"></script>
  
  <form>
  <div class="row">
    <div class="input-field col s6">
      <input class="validate" type="radio" name="mode" value="M" id="m" required="required" data-error="Error msg here">
      <label for="m">M</label>
    </div>
    <div class="input-field col s6">
      <input class="validate" type="radio" name="mode" value="F" id="f" required="required" data-error="Error msg here">
      <label for="f">F</label>
    </div>
    <div class="col s12" style="margin-top:20px">
    <button type="submit" class="waves-effect waves-green btn">
    Submit
    </button>
    </div>
  </div>
</form>

Why the error message is not displaying. Any help would be appreciated. Thanks.

like image 522
Ranjith Varatharajan Avatar asked Nov 08 '22 00:11

Ranjith Varatharajan


1 Answers

If you can use jQuery, you could implement a solution based on this fiddle.

By placing the group of radio buttons in a container div with class radioRequired:

<div class="col s12 radioRequired" name="mode" data-error="Error msg here">

JQuery can be used to check if there are any selected radio buttons with the name specified in the container. If there are none, highlight the div and add an error message with class radioWarning and text based on the data-error setting in the container. If a selection has been made, remove the highlight and the error message.

The radio buttons can be specified as:

  <input type="radio" name="mode" value="M" id="m">
  <label for="m">M</label>

Finally, if there are radioWarnings, prevent the default Submit action otherwise allow it as normal.

like image 137
chrisuae Avatar answered Nov 14 '22 21:11

chrisuae