Last active
February 17, 2016 09:32
-
-
Save sonianand11/5ed3abdc498e1f64ba3a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1) ActiveModel validation in rails server side : | |
class MyObject < ActiveRecord::Base | |
validates :state, :presence => true | |
validates :other_state, :presence => true, if: state.persent? | |
end | |
2) Lets say we have drop down with following state : | |
<select id="stateDropdown" name="state"> | |
<option value="state1">State1</option> | |
<option value="state2">State2</option> | |
<option value="state3">State3</option> | |
<option value="otherState">OtherState</option> | |
</select> | |
<input id="otherStateInput" type="text" name="other_state" readonly> | |
3) Javascript code to validate other state when user has selected `other` in state dropdown | |
// otherStatePresence function will check other state is selected, apply validator to input and exceutes validation | |
function otherStatePresence(e){ | |
var form,form_validators; | |
if( $("#stateDropdown option:selected").text().toLowerCase() == "otherstate"){ | |
form = $("#otherStateInput").closest("form") | |
form_validators = ClientSideValidations.forms[form.attr("id")].validators | |
form_validators["other_state"] = {"presence": [{"message": "can't be blank"}]} | |
}else{ | |
form = $("#otherStateInput").closest("form") | |
form_validators = ClientSideValidations.forms[form.attr("id")].validators | |
delete form_validators["other_state"] | |
} | |
form.resetClientSideValidations(); | |
return form.isValid(form_validators); | |
} | |
//Bind event on state dropdown, and don't allow user when user has selected state other than "OtherState" | |
$("#stateDropdown").on("change",function(event){ | |
if( $("#stateDropdown option:selected").text().toLowerCase() == "otherstate"){ | |
$("#otherStateInput").attr("readonly",false) | |
}else{ | |
$("#otherStateInput").attr("value","") | |
$("#otherStateInput").attr("readonly",true) | |
$("#otherStateInput").attr("data-validate",false) | |
} | |
}); | |
//check other state stuff before submitting form to server | |
$("#myObjectForm").submit(otherStatePresence); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment