我需要以格式不匹配和空字段的形式为文本字段设置自定义消息。
我已经在后端完成了所有验证,但是我也需要在前端进行验证。
文本域:
<%= f.text_field :id_number, pattern: "[0-9]*", required: true, oninvalid: "this.setCustomValidity('Only numbers allowed')", oninput: "setCustomValidity('')" %>
上面的方法在无效模式上可以正常工作,但是如果该字段为空,它还会显示相同的消息“仅允许数字”。
如何为适用于所有类型浏览器的不同错误设置不同的消息?
任何人都可以帮助..谢谢..
我正在添加我的答案-如何使用精彩的jquery.validate库进行客户端验证。
我正在使用版本 1.13.1
来了..
下载该库并将其放在app/assets/javascripts/jqueryValidation/dist
包含additional-methods.min.js
和的文件夹中jquery.validate.min.js
。
将库添加到资产管道中,以使其在全球范围内可用。
//= 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) {)
希望能帮助到你。:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句