Jquery validator does not work with selected

I just started working with the jquery validate plugin, but could not get it to work properly.

I have an example on Fiddle located at http://jsfiddle.net/GWABv/3/

Can someone tell me what the hell am I doing wrong? I'm just trying to require the user to select a parameter from the drop-down list, but even when I do not select a value, it returns, saying that the form is valid.

HTML:

<form id="roadForm" method="get" action=""> <p> <label for="editRoad_ProjectClassification"> <em class="red">*</em> Project Classification: </label> <select id="editRoad_ProjectClassification" name="editRoad_ProjectClassification" title="Please select something!" validate="required:true"> <option value="">Please select</option> <option value="1">1</option> <option value="2">2</option> </select> </p> </form> <label class="FUNC_saveRecord"> <span class="icon iconSave"></span> <span class="title">Save</span> </label> 

JavaScript:

 $('.FUNC_saveRecord').click(function() { saveRecord(); }); function saveRecord() { var roadFormValidator = $('#roadForm').validate(); if (!roadFormValidator.valid()) { roadFormValidator.showErrors(); } else { alert('form is valid'); } } 
+4
source share
1 answer

You have a few problems here:

  • form is written with an error in the opening tag ( <focm> ) It seems that this has been fixed.
  • You need to add the class='required' attribute to the field. validate=required:true will not do this.
  • You do not need to call validate every time a click occurs. Just calling it once on document.ready will be enough.
  • In this case, you do not need to manually call showErrors . The plugin will do this automatically for you.

This is how I will update your code:

HTML:

 <form id="roadForm" method="get" action=""> <p> <label for="editRoad_ProjectClassification"> <em class="red">*</em> Project Classification: </label> <select id="editRoad_ProjectClassification" name="editRoad_ProjectClassification" title="Please select something!" class="required"> <option value="">Please select</option> <option value="1">1</option> <option value="2">2</option> </select> </p> </form> <label class="FUNC_saveRecord"> <span class="icon iconSave"></span><span class="title">Save</span> </label> 

JavaScript:

 $("#roadForm").validate(); $('.FUNC_saveRecord').click(function() { saveRecord(); }); function saveRecord() { var roadFormValidator = $('#roadForm'); if (roadFormValidator.valid()) { alert('form is valid'); } } 

Example: http://jsfiddle.net/hRjJM/

+5
source

Source: https://habr.com/ru/post/1384482/


All Articles