Search code examples
javascriptvalidationmaterializeforms

How to validate my MaterializeCSS form, and if first value in select selected - do not send form & display an error?


I have done the following form with MaterializeCSS:

<form action="num.php" method="GET" autocomplete="off">
<select id="num" name="num" class="browser-default">
<option selected="true" disabled selected>Select number 
</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<button class="btn" type="submit">Show
<i class="material-icons right">send</i>
</button>
</form>

The problem is that the user can click on the button, without selecting a number. But I need that he first choose a value from the select, and only then press a button. And if he pressed a button without selecting a number (when "Select number:" selected), display an error and do not send the form. How can this be done with JavaScript?


Solution

  • no need for js. you can add required attribute to select and set value of Select number to ""

    <form action="num.php" onsubmit="return checkForm()"  method="GET" autocomplete="off">
    <select required id="num" name="num" class="browser-default">
    <option selected="true" value=""  disabled selected>Select number 
    </option>
    <option value="one">1</option>
    <option value="two">2</option>
    <option value="three">3</option>
    </select>
    <button class="btn" id="btn" type="submit">Show
    <i class="material-icons right">send</i>
    </button>
    </form>