我需要为表单中的文本字段设置自定义消息以应对模式不匹配和空字段。
我已在后端完成所有验证,但我还需要在前端执行此操作。
文本字段:
<%= f.text_field :id_number, pattern: "[0-9]*", required: true, oninvalid: "this.setCustomValidity('Only numbers allowed')", oninput: "setCustomValidity('')" %>
上面的方法在处理无效模式时效果很好,但如果字段为空,它也会显示相同的消息'Only numbers allowed'。
如何针对不同的错误设置不同的消息以适用于所有类型的浏览器?
请大家帮忙 谢谢..
最佳答案
我正在添加我的答案——如何使用精彩的jquery.validate library用于客户端验证。
我正在使用版本 1.13.1
开始了..
下载库并将其放在
app/assets/javascripts/jqueryValidation/dist
文件夹中,其中包括additional-methods.min.js
和jquery.validate.min.js
.将库添加到您的 Assets 管道,以便它在全局范围内可用。
//= require jqueryValidation/dist/jquery.validate //= require jqueryValidation/dist/additional-methods
开始在您的
_form.html.erb
中的表单上使用该库。<%= form_for(@new,:html=>{:id=>"newForm") do |f |%> //input fields with text/number/textarea etc <%end%>
初始化脚本并验证表单输入字段。
$("form#new_form").validate({ //use this to ignore autocomplete fields present,if any ignore: "", //set rules for input elements using name attribute rules: { "new_form[address]": "required", "new_form[tag]": "required", "new_form[title]": { required: true, minlength: 3, maxlength: 100 }, "new_form[contact_email]": { required: true, email: true, minlength: 5, maxlength: 100 }, "new_form_photos[avatar][]": { required: true, extension: "jpeg|jpg|png|gif" }, //use this to show custom dedicated placeholder message everytime validation fails...just like dynamic alert errorPlacement: function(error, element) { $("#show_error").html("<span class='text-danger' >Fields marked with * are required</span>"); }, //use this callback to get which field is currently failing validation and then add more custom logic if needed //for eg: you want to update the color of name label if validation fails. //validator.errorList contains an array of objects, where each object has properties "element" and "message". element is the actual HTML Input. invalidHandler: function(e,validator) { //use the key value pair to get => id=new_form_title, to identify your input field for (var i=0;i<validator.errorList.length;i++){ console.log(validator.errorList[i].element.attributes['id'].value); if ( validator.errorList[0].element.attributes['id'].value == "new_form_tag"){ //handle tag input field here by adding css/alert/focus etc } } } });//validation ends
同样,我们有submitHandler: function(form) {}
,onkeyup: function (element, event) {)
希望对您有所帮助。 :)
关于javascript - Rails - 为输入字段设置自定义验证消息(前端),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39010478/